2

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?

1
  • you don't need to propagate context, context is available globally. Commented Nov 26, 2017 at 13:00

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Nikhil Fadnis. It nice explanation. It fixed the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.