React - Context
About
A Context provides a way to pass data through the component tree without having to pass props down manually at every level.
Example: Translation
If you want to translate your application, you can use a context.
const englishMessages = message => {
if (message == "hello.world") {
return "Hello, World!";
}
return "Not yet translated";
};
const TranslationContext = React.createContext();
const Greeting = () => {
const translate = React.useContext(TranslationContext);
return <div>
<p>{translate("hello.world")}.</p>
<p>{translate("hello.you")}.</p>
</div>;
};
const App = () => (
<TranslationContext.Provider value={englishMessages}>
<Greeting />
</TranslationContext.Provider>
);
- And render
ReactDOM.render(<App />, document.getElementById('root'));
<div id="root"><!-- called the "root" DOM node because everything inside it will be managed by React DOM --></div>
- Output: