9

I am looking at the redux-blog-example. There is SignupRoute.js which looks like this:

@connect(state => ({
  auth: state.auth
}), {
  signup
})
export default class SignupRoute extends React.Component {
  static contextTypes = {
    router: React.PropTypes.object
  }

  handleSubmit = (email, password) => {
    const router = this.context.router;

    this.props.signup(email, password, router);
  }

  render() {
    return (
        <Signup
          auth={this.props}
          handleSubmit={this.handleSubmit}
        />
    );
  }
}

How does the router get wired up to the context of this class?

1 Answer 1

11

It uses context, an undocumented but quite widely implemented React feature. For a full lowdown see this article, but here's the gist of it:

let router = Router(); // just illustrating, this is not how you instantiate React router

class MyComponent extends React.Component {
    static contextTypes = {
        router: React.PropTypes.object
    };

    render(){
        // By declaring context type here, and childContextTypes
        // on the parent along with a function with how to get it,
        // React will traverse up and look for the `router` context.
        // It will then inject it into `this.context`, making it 
        // available here.
    }
}

class Parent extends React.Component {
    static childContextTypes = {
        router: React.PropTypes.object
    };

    getChildContext(){
      return {
        router: this.props.router
      };
    }

    render(){
        return <MyComponent />;
    }
}

ReactDOM.render(<Parent router={router} />, document.getElementById('app'));

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.