Created
October 7, 2016 21:52
-
-
Save AsaAyers/991c5cd15baf2ba9bbe322b65a0098f5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { Match } from 'react-router' | |
// example: | |
// <MatchWithTransforms | |
// transforms={{ id: Number }} | |
// pattern="/page/:id" | |
// component={ViewPage} /> | |
const MatchWithTransforms = ({ transforms, ...matchProps}) => { | |
const transformParams = (props) => { | |
const {...clonedParams} = props.params | |
Object.keys(transforms).forEach(key => { | |
if (clonedParams[key] != null) { | |
const transform = transforms[key] | |
clonedParams[key] = transform(clonedParams[key]) | |
} | |
}) | |
return { | |
...props, | |
params: clonedParams | |
} | |
} | |
/* matchProps is a shallow clone, so it's ok to modify */ | |
if (matchProps.component) { | |
const { component: Component } = matchProps | |
matchProps.component = (props) => ( | |
<Component {...transformParams(props)} /> | |
) | |
} | |
if (matchProps.render) { | |
const { render } = matchProps | |
matchProps.render = (props) => render(transformParams(props)) | |
} | |
if (typeof matchProps.children === 'function') { | |
const { children } = matchProps | |
matchProps.children = (props) => children(transformParams(props)) | |
} | |
return <Match {...matchProps} /> | |
} | |
MatchWithTransforms.propTypes = { | |
transforms: React.PropTypes.objectOf(React.PropTypes.func.isRequired,).isRequired, | |
} | |
export default MatchWithTransforms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment