Last active
November 13, 2017 03:30
-
-
Save jossmac/94bc58f55ac32d9da51643756cb91e58 to your computer and use it in GitHub Desktop.
A HOC for moving props to context. Used as a conduit to maintain context when rendering to a different subtree.
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, { Component } from 'react'; | |
import PropTypes from 'prop-types'; | |
const DefaultBaseComponent = props => <div {...props} />; | |
const withContextFromProps = ( | |
propTypes: PropTypes.object, | |
BaseComponent: PropTypes.func = DefaultBaseComponent | |
) => { | |
class ContextProps extends Component { | |
static propTypes = { children: PropTypes.node } | |
getChildContext() { | |
const props = Object.keys(this.props).reduce((result, key) => { | |
if (key !== 'children') result[key] = this.props[key]; | |
return result; | |
}, {}); | |
return props; | |
} | |
render() { | |
return <BaseComponent>{this.props.children}</BaseComponent>; | |
} | |
} | |
ContextProps.displayName = 'withContextFromProps'; | |
ContextProps.childContextTypes = propTypes; | |
return ContextProps; | |
}; | |
export default withContextFromProps; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment