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

Is there an easier way to access an object Router

from a component in order to do things like call transitionTo()

without using nav mixing? This is an ES6 component. Currently, in an event like a button click, I write 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>
    );
  }
}

      

+3


source to share


1 answer


Per Mat Gessel's comment , adding 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
};

      

+8


source







All Articles