Skip to content

Instantly share code, notes, and snippets.

@adi518
Last active August 5, 2019 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adi518/5c3e8784c1f590b233b44d1367083cda to your computer and use it in GitHub Desktop.
Save adi518/5c3e8784c1f590b233b44d1367083cda to your computer and use it in GitHub Desktop.
import React from "react";
import { merge, compose } from "lodash/fp";
export const castRouterParams = (keys, caster) => WrappedComponent => ({
match,
...props
}) => {
const params = Object.fromEntries(
keys.map(key => {
const value = match.params[key];
return [key, value ? caster(value) : undefined];
})
);
return (
<WrappedComponent
{...props}
{...{ match: { params: merge({}, match.params, params) } }}
/>
);
};
export const flattenRouterParams = WrappedComponent => ({
match,
...props
}) => {
return <WrappedComponent {...props} {...match.params} />;
};
// usage:
const FooComponent = props => {
console.log(typeof props.match.params.someId) // "number"
}
export default compose(
withRouter,
castRouterParams(["someIdProp", "otherIdProp"], Number)
)(FooComponent);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment