Last active
August 5, 2019 21:17
-
-
Save adi518/5c3e8784c1f590b233b44d1367083cda to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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