Created
April 8, 2018 20:42
-
-
Save crash7/583cc5216752f8033a4aa97197fc6240 to your computer and use it in GitHub Desktop.
Playing with the new React Context API
This file contains hidden or 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
/** | |
* This a very small example of a HoC that used the new react context API that can be used to save a | |
* state globally without using any state library. | |
* | |
* This is a toy gist just to demo what you can do, please don't copy & paste the code without reading: | |
* https://reactjs.org/docs/context.htmt | |
*/ | |
import React, { PureComponent } from 'react'; | |
const defaultContextValue = { | |
something: "blue" | |
}; | |
const { Provider, Consumer } = React.createContext(); | |
export class DemoContextProvider extends PureComponent { | |
state = { | |
something: 'borrow', | |
doing: 0 | |
} | |
constructor(props) { | |
super(props); | |
this.state.doSomething = this.doSomething | |
} | |
doSomething = () => { | |
this.setState((prevState) => ({ doing: ++prevState.doing })); | |
} | |
render() { | |
return ( | |
<Provider value={this.state}> | |
{this.props.children} | |
</Provider> | |
); | |
} | |
} | |
export const withDemoContext = WrappedComponent => (props) => { | |
return ( | |
<Consumer> | |
{context => <WrappedComponent {...props} demoContext={context} />} | |
</Consumer> | |
); | |
} | |
export default { DemoContextProvider, withDemoContext }; |
This file contains hidden or 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 { withDemoContext } from './DemoContext'; | |
const StatelessButton = ({ demoContext }) => { | |
return ( | |
<div> | |
it was called {`${demoContext.doing}`} times | |
<button onClick={demoContext.doSomething}>test</button> | |
</div> | |
); | |
} | |
const ThemedButton = withDemoContext(StatelessButton); |
This file contains hidden or 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 { DemoContextProvider } from './DemoContext'; | |
ReactDOM.render( | |
<DemoContextProvider> | |
<App /> | |
</DemoContextProvider>, | |
document.getElementById('root')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment