React Router 1.0 using router.transitionTo() without Navigation mixin

By : Brad
Source: Stackoverflow.com
Question!

Is there an easier way to access the Router object from a component to do things like call transitionTo() without using the Navigation mixin? This is an ES6 component. Currently on an event like a button click, I have been writing something like this:

class Button extends React.Component {
  handleClick(e) {
    e.preventDefault();
    var router = this._reactInternalInstance._context.router;
    router.transitionTo('/search');
  }

  render() {
    return (
      <button onClick={this.handleClick.bind(this)}>
        {this.props.children}
      </button>
    );
  }
}
By : Brad


Answers
Per Mat Gessel's comment, adding the context as a parameter in the constructor will give you access to the router.

class Button extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.context = context;      
  }

  handleClick(e) {
    e.preventDefault();
    this.context.router.transitionTo('/search');
  }

  render() {
    return (
      <button onClick={this.handleClick.bind(this)}>
        {this.props.children}
      </button>
    );
  }
}

Button.contextTypes = {
  router: React.PropTypes.object.isRequired
};
By : Brad


This video can help you solving your question :)
By: admin