Skip to content

Instantly share code, notes, and snippets.

@export-mike
Created November 8, 2017 00:43
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 export-mike/78f02bef3019b6affb53a63ee314262e to your computer and use it in GitHub Desktop.
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.
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