Created
April 24, 2019 15:17
-
-
Save verdi327/8bbd8963d4329dbf0051a20415034299 to your computer and use it in GitHub Desktop.
context overview
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
UserContext.js | |
-define the user context | |
const UserContext = React.createContext({ | |
name: 'Joe', | |
setName: () => {} | |
}); | |
-- | |
App.js | |
-import user context | |
-within your render - set the values from state | |
<UserContext.Provider value={{ | |
name: this.state.name, | |
setName: name => this.setState({name}) | |
}}> | |
<Child /> | |
</UserContext.Provider> | |
class Component | |
Some Distant Child Component | |
-import user context file | |
-set static ContextType = UserContext; | |
-now can call this.context.somePropName | |
stateless Component | |
-import user context file | |
-Inside return, return JSX from UserContext | |
<UserContext.Consumer> | |
{({name, setName}) => ( | |
<div className="user" onClick={() => setName('Chris')}> | |
{name} | |
</div> | |
)} | |
</UserContext.Consumer> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment