how to propagate context to Router component. Reactjs

Viewed 59

I want to make logged user's data global in my reactjs app. My App code:

class App extends Component {
  getChildContext = () => {
    return {
      user: {
       name: 'username',
       email: 'email@rmail.com'
      }
    }
  }

  render() {
    return (
    <Router>
      <div>
        <Route exact path='/game' component={Game} />
        <Route exact path='/singup' component={Singup} />
      </div>
    </Router>
  );
 }

App.childContextTypes = {
 user: PropTypes.object
};

In Game component I try to get use through this.context.user but I get undefined.

Can I propagate context to Router component?

1 Answers

By adding childContextTypes and getChildContext to the context provider, React passes the information down automatically and any component in the subtree can access it by defining contextTypes. If contextTypes is not defined, then context will be an empty object.

Make sure you've defined contextTypes on your Game component

Game.contextTypes = {
  user: PropTypes.object
};

https://reactjs.org/docs/context.html

Related