Ivan Hreskiv
Ivan Hreskiv

Reputation: 1075

how to propagate context to Router component. Reactjs

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 protected]'
      }
    }
  }

  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?

Upvotes: 2

Views: 83

Answers (1)

Nikhil Fadnis
Nikhil Fadnis

Reputation: 860

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

Upvotes: 1

Related Questions