reactjs - Programmatically navigate using React router

ID : 473

viewed : 215

Tags : reactjsreact-routerreactjs





Top 5 Answer for reactjs - Programmatically navigate using React router

vote vote

95

React Router v5.1.0 with hooks

There is a new useHistory hook in React Router >5.1.0 if you are using React >16.8.0 and functional components.

import { useHistory } from "react-router-dom";  function HomeButton() {   const history = useHistory();    function handleClick() {     history.push("/home");   }    return (     <button type="button" onClick={handleClick}>       Go home     </button>   ); } 

React Router v4

With v4 of React Router, there are three approaches that you can take to programmatic routing within components.

  1. Use the withRouter higher-order component.
  2. Use composition and render a <Route>
  3. Use the context.

React Router is mostly a wrapper around the history library. history handles interaction with the browser's window.history for you with its browser and hash histories. It also provides a memory history which is useful for environments that don't have a global history. This is particularly useful in mobile app development (react-native) and unit testing with Node.

A history instance has two methods for navigating: push and replace. If you think of the history as an array of visited locations, push will add a new location to the array and replace will replace the current location in the array with the new one. Typically you will want to use the push method when you are navigating.

In earlier versions of React Router, you had to create your own history instance, but in v4 the <BrowserRouter>, <HashRouter>, and <MemoryRouter> components will create a browser, hash, and memory instances for you. React Router makes the properties and methods of the history instance associated with your router available through the context, under the router object.

1. Use the withRouter higher-order component

The withRouter higher-order component will inject the history object as a prop of the component. This allows you to access the push and replace methods without having to deal with the context.

import { withRouter } from 'react-router-dom' // this also works with react-router-native  const Button = withRouter(({ history }) => (   <button     type='button'     onClick={() => { history.push('/new-location') }}   >     Click Me!   </button> )) 

2. Use composition and render a <Route>

The <Route> component isn't just for matching locations. You can render a pathless route and it will always match the current location. The <Route> component passes the same props as withRouter, so you will be able to access the history methods through the history prop.

import { Route } from 'react-router-dom'  const Button = () => (   <Route render={({ history}) => (     <button       type='button'       onClick={() => { history.push('/new-location') }}     >       Click Me!     </button>   )} /> ) 

3. Use the context*

But you probably should not

The last option is one that you should only use if you feel comfortable working with React's context model (React's Context API is stable as of v16).

const Button = (props, context) => (   <button     type='button'     onClick={() => {       // context.history.push === history.push       context.history.push('/new-location')     }}   >     Click Me!   </button> )  // you need to specify the context type so that it // is available within the component Button.contextTypes = {   history: React.PropTypes.shape({     push: React.PropTypes.func.isRequired   }) } 

1 and 2 are the simplest choices to implement, so for most use cases, they are your best bets.

vote vote

83

React-Router v6+ Answer

You can use the new useNavigate hook. useNavigate hook returns a function which can be used for programmatic navigation. Example from the react router documentaion

import { useNavigate } from "react-router-dom";  function SignupForm() {   let navigate = useNavigate();    async function handleSubmit(event) {     event.preventDefault();     await submitForm(event.target);     navigate("../success", { replace: true });   }    return <form onSubmit={handleSubmit}>{/* ... */}</form>; } 

React-Router 5.1.0+ Answer (using hooks and React >16.8)

You can use the useHistory hook on Functional Components and Programmatically navigate:

import { useHistory } from "react-router-dom";  function HomeButton() {   let history = useHistory();   // use history.push('/some/path') here }; 

React-Router 4.0.0+ Answer

In 4.0 and above, use the history as a prop of your component.

class Example extends React.Component {    // use `this.props.history.push('/some/path')` here }; 

NOTE: this.props.history does not exist in the case your component was not rendered by <Route>. You should use <Route path="..." component={YourComponent}/> to have this.props.history in YourComponent

React-Router 3.0.0+ Answer

In 3.0 and above, use the router as a prop of your component.

class Example extends React.Component {    // use `this.props.router.push('/some/path')` here }; 

React-Router 2.4.0+ Answer

In 2.4 and above, use a higher order component to get the router as a prop of your component.

import { withRouter } from 'react-router';  class Example extends React.Component {    // use `this.props.router.push('/some/path')` here };  // Export the decorated class var DecoratedExample = withRouter(Example);  // PropTypes Example.propTypes = {   router: React.PropTypes.shape({     push: React.PropTypes.func.isRequired   }).isRequired }; 

React-Router 2.0.0+ Answer

This version is backwards compatible with 1.x so there's no need to an Upgrade Guide. Just going through the examples should be good enough.

That said, if you wish to switch to the new pattern, there's a browserHistory module inside the router that you can access with

import { browserHistory } from 'react-router'

Now you have access to your browser history, so you can do things like push, replace, etc... Like:

browserHistory.push('/some/path')

Further reading: Histories and Navigation


React-Router 1.x.x Answer

I will not go into upgrading details. You can read about that in the Upgrade Guide

The main change about the question here is the change from Navigation mixin to History. Now it's using the browser historyAPI to change route so we will use pushState() from now on.

Here's an exemple using Mixin:

var Example = React.createClass({   mixins: [ History ],   navigateToHelpPage () {     this.history.pushState(null, `/help`);   } }) 

Note that this History comes from rackt/history project. Not from React-Router itself.

If you don't want to use Mixin for some reason (maybe because of ES6 class), then you can access the history that you get from the router from this.props.history. It will be only accessible for the components rendered by your Router. So, if you want to use it in any child components it needs to be passed down as an attribute via props.

You can read more about the new release at their 1.0.x documentation

Here is a help page specifically about navigating outside your component

It recommends grabbing a reference history = createHistory() and calling replaceState on that.

React-Router 0.13.x Answer

I got into the same problem and could only find the solution with the Navigation mixin that comes with react-router.

Here's how I did it

import React from 'react'; import {Navigation} from 'react-router';  let Authentication = React.createClass({   mixins: [Navigation],    handleClick(e) {     e.preventDefault();      this.transitionTo('/');   },    render(){     return (<div onClick={this.handleClick}>Click me!</div>);   } }); 

I was able to call transitionTo() without the need to access .context

Or you could try the fancy ES6 class

import React from 'react';  export default class Authentication extends React.Component {   constructor(props) {     super(props);     this.handleClick = this.handleClick.bind(this);   }    handleClick(e) {     e.preventDefault();      this.context.router.transitionTo('/');   }    render(){     return (<div onClick={this.handleClick}>Click me!</div>);   } }  Authentication.contextTypes = {   router: React.PropTypes.func.isRequired }; 

React-Router-Redux

Note: if you're using Redux, there is another project called React-Router-Redux that gives you redux bindings for ReactRouter, using somewhat the same approach that React-Redux does

React-Router-Redux has a few methods available that allow for simple navigating from inside action creators. These can be particularly useful for people that have existing architecture in React Native, and they wish to utilize the same patterns in React Web with minimal boilerplate overhead.

Explore the following methods:

  • push(location)
  • replace(location)
  • go(number)
  • goBack()
  • goForward()

Here is an example usage, with Redux-Thunk:

./actioncreators.js

import { goBack } from 'react-router-redux'  export const onBackPress = () => (dispatch) => dispatch(goBack()) 

./viewcomponent.js

<button   disabled={submitting}   className="cancel_button"   onClick={(e) => {     e.preventDefault()     this.props.onBackPress()   }} >   CANCEL </button> 
vote vote

73

React-Router v2

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 in the Navigating outside of Components doc.

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 used to change the URL, not to actually navigate to the page.

vote vote

69

Here's how you do this with react-router v2.0.0 with ES6. react-router has moved away from mixins.

import React from 'react';  export default class MyComponent extends React.Component {   navigateToPage = () => {     this.context.router.push('/my-route')   };    render() {     return (       <button onClick={this.navigateToPage}>Go!</button>     );   } }  MyComponent.contextTypes = {   router: React.PropTypes.object.isRequired } 
vote vote

54

React-Router 4.x answer

On my end, I like to have a single history object that I can carry even outside components. I like to have a single history.js file that I import on demand, and just manipulate it.

You just have to change BrowserRouter to Router, and specify the history prop. This doesn't change anything for you, except that you have your own history object that you can manipulate as you want.

You need to install history, the library used by react-router.

Example usage, ES6 notation:

history.js

import createBrowserHistory from 'history/createBrowserHistory' export default createBrowserHistory() 

BasicComponent.js

import React, { Component } from 'react'; import history from './history';  class BasicComponent extends Component {      goToIndex(e){         e.preventDefault();         history.push('/');     }      render(){         return <a href="#" onClick={this.goToIndex}>Previous</a>;     } } 

If you have to navigate from a component that is actually rendered from a Route component, you can also access history from props, like that:

BasicComponent.js

import React, { Component } from 'react';  class BasicComponent extends Component {      navigate(e){         e.preventDefault();         this.props.history.push('/url');     }      render(){         return <a href="#" onClick={this.navigate}>Previous</a>;     } } 

Top 3 video Explaining reactjs - Programmatically navigate using React router







Related QUESTION?