Advertisement
Guest User

Untitled

a guest
Aug 17th, 2019
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. import React from "react";
  2. import { merge, compose } from "lodash/fp";
  3.  
  4. export const castRouterParams = (keys, caster) => WrappedComponent => ({
  5. match,
  6. ...props
  7. }) => {
  8. const params = Object.fromEntries(
  9. keys.map(key => {
  10. const value = match.params[key];
  11. return [key, value ? caster(value) : undefined];
  12. })
  13. );
  14. return (
  15. <WrappedComponent
  16. {...props}
  17. {...{ match: { params: merge({}, match.params, params) } }}
  18. />
  19. );
  20. };
  21.  
  22. export const flattenRouterParams = WrappedComponent => ({
  23. match,
  24. ...props
  25. }) => {
  26. return <WrappedComponent {...props} {...match.params} />;
  27. };
  28.  
  29. // usage:
  30. const FooComponent = props => {
  31. console.log(typeof props.match.params.someId) // "number"
  32. }
  33.  
  34. export default compose(
  35. withRouter,
  36. castRouterParams(["someIdProp", "otherIdProp"], Number)
  37. )(FooComponent);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement