Is there an easier way to access the Router
object from a ponent to do things like call transitionTo()
without using the Navigation mixin? This is an ES6 ponent. 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>
);
}
}
Is there an easier way to access the Router
object from a ponent to do things like call transitionTo()
without using the Navigation mixin? This is an ES6 ponent. 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>
);
}
}
Share
Improve this question
asked Jul 17, 2015 at 5:45
BradBrad
1,8991 gold badge12 silver badges18 bronze badges
3
-
Confused, why not just
this.context.router
? – Henrik Andersson Commented Jul 17, 2015 at 5:48 - 5 Contexts in ES6 is undocumented at the moment. You accept the context in a parameter of the constructor and pass the context to the super. You can then access the context normally. Code examples in this react-router issue. – Mat Gessel Commented Jul 17, 2015 at 6:41
- Thanks @MatGessel!! I'll document the solution below. – Brad Commented Jul 17, 2015 at 13:37
1 Answer
Reset to default 8Per Mat Gessel's ment, 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
};