-
Notifications
You must be signed in to change notification settings - Fork 0
33 Context API
Context Context provides a means of passing state down the component tree through a Provider/Consumer relationship.
At as high a level as makes sense, a "provider" can make it's state available, along with means of altering it (methods).
import React from 'react';
export const SettingsContext = React.createContext();
class SettingsProvider extends React.Component { constructor(props) { super(props); this.state = { changeTitleTo: this.changeTitleTo, title: 'My Amazing Website', }; }
changeTitleTo = title => { this.setState({ title }); };
render() { return ( <SettingsContext.Provider value={this.state}> {this.props.children} </SettingsContext.Provider> ); } }
export default SettingsProvider;
At the app level ...
At the lower levels any component can "opt-in" and become a "consumer" and receive state and potentially methods through it. Note the wrapping of context in a component, and the requirement of using a function to "get" the context object itself, which is this.state from the provider component.<SettingsContext.Consumer> {context => { console.log(context); return (
); }} </SettingsContext.Consumer>