react-higher-order
react-higher-order copied to clipboard
☔️ Maps render props to a higher order component
npm install react-higher-order
The old problem ...
const RenderProps = ({ children }) => children({ value: 123 })
class Test extends React.Component {
componentDidUpdate() {
// How the hell do i access render props in here???
}
render() {
return <RenderProps>{props => props.value}</RenderProps>
}
}
And the solution ...
import hoc from 'react-higher-order'
const RenderProps = ({ children }) => children({ value: 123 })
@hoc(RenderProps, (props, ownProps) => ({ number: props[ownProps.accessor] }))
class Test extends React.Component {
componentDidUpdate() {
console.log(this.props.number)
}
render() {
return this.props.number
}
}
ReactDOM.render(<Test accessor="value" />, document.querySelector('#root'))
API
hoc(RenderPropsComponent, mapRenderPropsToProps = props => props)(WrappedComponent)
RenderPropsComponentis the component you want to fold intomapRenderPropsToPropsis optional and defaults toprops => props, use it to pick the props you are interested in. You can also use this to selectively access only a portion of the RenderPropComponent's props, your own component will then only render if these props change. You have access to the components own-props as a second argument.WrappedComponentis the component that is going to receive the props.
Contributions
All my open source projects are done in my free time, if you like any of them, consider helping out, all contributions are welcome as well as donations, for instance through Patreon.