React - Context

React Mapping Html Javascript

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:

1)





Recommended Pages
React Mapping Html Javascript
React - Dependency Injection

in React (via parent/children) Interface: only via Typescript
React Props Chrome Plugin
React - Props

props is the only object argument passed from a component to another component. Props are similar to State, but is public and not fully controlled by the component. You can also pass arguments to...



Share this page:
Follow us:
Task Runner