Skip to content

Instantly share code, notes, and snippets.

@AsaAyers
Created October 7, 2016 21:52
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 AsaAyers/991c5cd15baf2ba9bbe322b65a0098f5 to your computer and use it in GitHub Desktop.
Save AsaAyers/991c5cd15baf2ba9bbe322b65a0098f5 to your computer and use it in GitHub Desktop.
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