Reputation: 1899
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>
);
}
}
Upvotes: 3
Views: 2782
Reputation: 1899
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
};
Upvotes: 8