Created
May 4, 2018 16:10
-
-
Save markadamfoster/bbaaf2e8e2f131eb1d848dcf167317f1 to your computer and use it in GitHub Desktop.
React Context API (with notes)
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' | |
/* | |
STEP 1: Create the new Context | |
- starts with capital letter | |
- can (optionally) pass in default context values to the .createContext() call | |
*/ | |
const CurrentUserContext = React.createContext() | |
/* | |
STEP 2: Create the Provider | |
- Should return something like this: | |
<CONTEXT_NAME.Provider value={}> | |
{this.props.children} | |
</CONTEXT_NAME.Provider> | |
- anything passed down on the value prop will later be available to the consumer. | |
*/ | |
class CurrentUserProvider extends Component { | |
state = { | |
id: '1234abcdef', | |
username: 'studmuffin', | |
firstName: 'Mark' | |
} | |
render() { | |
return ( | |
<CurrentUserContext.Provider | |
value={{ | |
state: this.state, | |
updateFirstName: val => this.setState({ firstName: val }) | |
}} | |
> | |
{this.props.children} | |
</CurrentUserContext.Provider> | |
) | |
} | |
} | |
/* | |
STEP 4: The Consumer | |
- Looks something like this: | |
<CONTEXT_NAME.Consumer> | |
{context => ()} | |
</CONTEXT_NAME.Consumer> | |
- the `context` render prop allows access to Provider's data passed down via value prop | |
*/ | |
class CurrentUser extends Component { | |
render() { | |
return ( | |
<div className="currentUser"> | |
<CurrentUserContext.Consumer> | |
{context => ( | |
<div> | |
<p>Username: {context.state.username}</p> | |
<p>Name: {context.state.firstName}</p> | |
<input | |
value={context.state.firstName} | |
onChange={e => context.updateFirstName(e.target.value)} | |
/> | |
</div> | |
)} | |
</CurrentUserContext.Consumer> | |
</div> | |
) | |
} | |
} | |
/* | |
These demonstrate the ability for consumers to access data multiple levels deep | |
*/ | |
const AccountPanel = () => ( | |
<div className="account"> | |
<CurrentUser /> | |
</div> | |
) | |
const SettingsPage = () => ( | |
<div className="settings"> | |
<AccountPanel /> | |
</div> | |
) | |
/* | |
STEP 3: Wrap with the Provider | |
*/ | |
class App extends Component { | |
render() { | |
return ( | |
<CurrentUserProvider> | |
<div className="App"> | |
<SettingsPage /> | |
</div> | |
</CurrentUserProvider> | |
) | |
} | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment