George Mauer George Mauer - 2 months ago 115
React JSX Question

Programmatically navigate using react router

With

react-router
I can use the
Link
element to create links that are natively handled by react router.

I see internally it calls
this.context.transitionTo(...)
.

I want to do a navigation, but not from a link, from a dropdown selection for example. How can I do this in code? What is
this.context
?

I saw the
Navigation
mixin, but can I do this without mixins?

Answer

for the most recent release (v2.0.0-rc5), the recommended navigation method is by directly pushing onto the history singleton. You can see that in action here. Relevant excerpt:

import { browserHistory } from './react-router'
browserHistory.push('/some/path')

If using the newer react-router API, you need to make use of the history from this.props when inside of components so:

this.props.history.push('/some/path');

It also offers pushState but that is deprecated per logged warnings.

If using react-router-redux, it offers a push function you can dispatch like so:

import { push } from 'react-router-redux';
this.props.dispatch(push('/some/path'));

However this may be only to change the URL not actually navigate to the page.

Comments