Created
November 8, 2017 00:43
-
-
Save export-mike/78f02bef3019b6affb53a63ee314262e to your computer and use it in GitHub Desktop.
ReactProviderFactory.js - create simple providers with accompanying higher order 'with' components to access context.
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'; | |
export default (propName, propType, contextProp) => { | |
return { | |
Provider: createProvider(propName, propType, contextProp), | |
Hoc: createHigherOrderComponent(propName, propType, contextProp) | |
} | |
}; | |
export const createProvider = (propName, propType, contextProp) => class Provider extends Component { | |
static childContextTypes = { | |
[contextProp]: PropTypes[propType] | |
}; | |
getChildContext() { | |
return {[contextProp]: this.props[propName]}; | |
} | |
render() { | |
return this.props.children; | |
} | |
} | |
export const createHigherOrderComponent = (propName, propType, contextProp) => WrappedComponent => class withHoc extends Component { | |
static contextTypes = { | |
[contextProp]: PropTypes[propType] | |
}; | |
render(){ | |
return <WrappedComponent {...this.context} {...this.props}/> | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment