Context is designed to share data that can be considered global for a tree of React components.
For example, in the code below lets manually thread through a “theme” prop in order to style the Button component.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | //Lets create a context with a default theme value "luna" const ThemeContext = React.createContext('luna'); // Create App component where it uses provider to pass theme value in the tree class App extends React.Component { render() { return ( <ThemeContext.Provider value="nova"> <Toolbar /> </ThemeContext.Provider> ); } } // A middle component where you don't need to pass theme prop anymore function Toolbar(props) { return ( <div> <ThemedButton /> </div> ); } // Lets read theme value in the button component to use class ThemedButton extends React.Component { static contextType = ThemeContext; render() { return <Button theme={this.context} />; } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.