Last active
November 8, 2017 00:53
-
-
Save export-mike/ee4bc793ccac1a7dd611b0f432569c2b 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}/> | |
} | |
} | |
/* USAGE */ | |
// DebugProvider.js | |
import ReactProviderFactory from './ReactProviderFactory'; | |
const Debug = ReactProviderFactory('debug', 'func', 'debug'); | |
export const withDebug = Debug.Hoc; | |
export default Debug.Provider; | |
// App.js | |
import debug from 'debug'; | |
import { Router, Route } from 'react-router-dom'; | |
import Users from './Users'; | |
class App extends Component { | |
render() { | |
return <DebugProvider debug={debug}> | |
<Router> | |
<Route path="/users" component={Users} /> | |
</Router> | |
</DebugProvider> | |
} | |
} | |
// User.js | |
import { withDebug } from './DebugProvider'; | |
class Users extends Component { | |
componentDidMount() { | |
const userDebug = this.props.debug('users'); | |
userDebug('Mounted!'); | |
} | |
render() { | |
return <div> Users </div> | |
} | |
} | |
export default withDebug(Users); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment