[reactjs] Programmatically navigate using React router

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

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

I want to do a navigation. Not from a link, but from a dropdown selection (as an example). How can I do this in code? What is this.context?

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

This question is related to reactjs react-router

The answer is


react-router-dom: 5.1.2

  • This site has 3 pages, all of which are rendered dynamically in the browser.

  • Although the page does not ever refresh, notice how React Router keeps the URL up to date as you navigate through the site. This preserves the browser history, making sure things like the back button and bookmarks work properly

  • A Switch looks through all its children elements and renders the first one whose path matches the current URL. Use a any time you have multiple routes, but you want only one of them to render at a time

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";



export default function BasicExample() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/dashboard">Dashboard</Link>
          </li>
        </ul>

        <hr />

        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/dashboard">
            <Dashboard />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

// You can think of these components as "pages"
// in your app.

function Home() {
  return (
    <div>
      <h2>Home</h2>
    </div>
  );
}

function About() {
  return (
    <div>
      <h2>About</h2>
    </div>
  );
}

function Dashboard() {
  return (
    <div>
      <h2>Dashboard</h2>
    </div>
  );
}```

For ES6 + React components, the following solution worked for me.

I followed Felippe skinner, but added an end to end solution to help beginners like me.

Below are the versions I used:

"react-router": "^2.7.0"

"react": "^15.3.1"

Below is my react component where I used programmatic navigation using react-router:

import React from 'react';

class loginComp extends React.Component {
   constructor( context) {
    super(context);
    this.state = {
      uname: '',
      pwd: ''
    };
  }

  redirectToMainPage(){
        this.context.router.replace('/home');
  }

  render(){
    return <div>
           // skipping html code 
             <button onClick={this.redirectToMainPage.bind(this)}>Redirect</button>
    </div>;
  }
};

 loginComp.contextTypes = {
    router: React.PropTypes.object.isRequired
 }

 module.exports = loginComp;

Below is the configuration for my router:

 import { Router, Route, IndexRedirect, browserHistory } from 'react-router'

 render(<Router history={browserHistory}>
          <Route path='/' component={ParentComp}>
            <IndexRedirect to = "/login"/>
            <Route path='/login' component={LoginComp}/>
            <Route path='/home' component={HomeComp}/>
            <Route path='/repair' component={RepairJobComp} />
            <Route path='/service' component={ServiceJobComp} />
          </Route>
        </Router>, document.getElementById('root'));

In React-Router v4 and ES6

You can use withRouter and this.props.history.push.

import {withRouter} from 'react-router-dom';

class Home extends Component {

    componentDidMount() {
        this.props.history.push('/redirect-to');
    }
}

export default withRouter(Home);

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

You can use the new 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>

based on the previous answer
from José Antonio Postigo and Ben Wheeler
the novelty? is to be written in Typescript
and the use of decorators
OR static property/field

import * as React from "react";
import Component = React.Component;
import { withRouter } from "react-router";

export interface INavigatorProps {
    router?: ReactRouter.History.History;
}

/**
 * Note: goes great with mobx 
 * @inject("something") @withRouter @observer
 */
@withRouter
export class Navigator extends Component<INavigatorProps, {}>{
    navigate: (to: string) => void;
    constructor(props: INavigatorProps) {
        super(props);
        let self = this;
        this.navigate = (to) => self.props.router.push(to);
    }
    render() {
        return (
            <ul>
                <li onClick={() => this.navigate("/home")}>
                    Home
                </li>
                <li onClick={() => this.navigate("/about")}>
                    About
                </li>
            </ul>
        )
    }
}

/**
 * Non decorated 
 */
export class Navigator2 extends Component<INavigatorProps, {}> {

    static contextTypes = {
        router: React.PropTypes.object.isRequired,
    };

    navigate: (to: string) => void;
    constructor(props: INavigatorProps, context: any) {
        super(props, context);
        let s = this;
        this.navigate = (to) =>
            s.context.router.push(to);
    }
    render() {
        return (
            <ul>
                <li onClick={() => this.navigate("/home")}>
                    Home
                </li>
                <li onClick={() => this.navigate("/about")}>
                    About
                </li>
            </ul>
        )
    }
}

with whatever npm installed today. "react-router": "^3.0.0" and
"@types/react-router": "^2.0.41"


EDIT: React Router v6

I haven't touched React in a while, but want to thank and highlight the comment below by @Shimrit Snapir

on React-Router 6.0 <Redirect /> changed to <Navigate />

React Router V4

tl:dr;

if (navigate) {
  return <Redirect to="/" push={true} />
}

The simple and declarative answer is that you need to use <Redirect to={URL} push={boolean} /> in combination with setState()

push: boolean - when true, redirecting will push a new entry onto the history instead of replacing the current one.


import { Redirect } from 'react-router'

class FooBar extends React.Component {
  state = {
    navigate: false
  }

  render() {
    const { navigate } = this.state
    
    // here is the important part
    if (navigate) {
      return <Redirect to="/" push={true} />
    }
   // ^^^^^^^^^^^^^^^^^^^^^^^
    
    return (
      <div>
        <button onClick={() => this.setState({ navigate: true })}>
          Home
        </button>
      </div>
    )
  }
}

Full example here. Read more here.

PS. The example uses ES7+ Property Initializers to initialise state. Look here as well, if you're interested.


I tried at least 10 ways of doing this before something worked right!

@Felipe Skinner's withRouter answer was a bit overwhelming to me, and I wasn't sure I wanted to make new "ExportedWithRouter" class names.

Here's the simplest and cleanest way to do it, circa current React-Router 3.0.0 and ES6:

React-Router 3.x.x with ES6:

import { withRouter } from 'react-router';

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

// Export the decorated class
export default withRouter(Example);

or, if it's not your default class, export like:

withRouter(Example);
export { Example };

Note that in 3.x.x, the <Link> component itself is using router.push, so you can pass it anything you would pass the <Link to= tag, like:

   this.props.router.push({pathname: '/some/path', query: {key1: 'val1', key2: 'val2'})'

If you are using hash or browser history then you can do

hashHistory.push('/login');
browserHistory.push('/login');

For React Router v4+

Assuming that you won't be needing to navigate during the initial render itself (for which you can use <Redirect> component), this is what we are doing in our app.

Define an empty route which returns null, this will allow you to get the access to the history object. You need to do this at the top level where your Router is defined.

Now you can do all the things that can be done on history like history.push(), history.replace(), history.go(-1) etc!

import React from 'react';
import { HashRouter, Route } from 'react-router-dom';

let routeHistory = null;

export function navigateTo(path) {
  if(routeHistory !== null) {
    routeHistory.push(path);
  }
}

export default function App(props) {
  return (
    <HashRouter hashType="noslash">
      <Route
        render={({ history }) => {
          routeHistory = history;
          return null;
        }}
      />
      {/* Rest of the App */}
    </HashRouter>
  );
}

You can also use the useHistory hook in a stateless component. Example from the docs.

import { useHistory } from "react-router"

function HomeButton() {
  const history = useHistory()

  return (
    <button type="button" onClick={() => history.push("/home")}>
      Go home
    </button>
  )
}

Note: Hooks were added in [email protected] and require react@>=16.8


To do the navigation programmatically, you need to push a new history to the props.history in your component, so something like this can do the work for you:

//using ES6
import React from 'react';

class App extends React.Component {

  constructor(props) {
    super(props)
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick(e) {
    e.preventDefault()
    /* Look at here, you can add it here */
    this.props.history.push('/redirected');
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>
          Redirect!!!
        </button>
      </div>
    )
  }
}

export default App;

Warning: this answer covers only ReactRouter versions before 1.0

I will update this answer with 1.0.0-rc1 use cases after!

You can do this without mixins too.

let Authentication = React.createClass({
  contextTypes: {
    router: React.PropTypes.func
  },
  handleClick(e) {
    e.preventDefault();
    this.context.router.transitionTo('/');
  },
  render(){
    return (<div onClick={this.handleClick}>Click me!</div>);
  }
});

The gotcha with contexts is that it is not accessible unless you define the contextTypes on the class.

As for what is context, it is an object, like props, that are passed down from parent to child, but it is passed down implicitly, without having to redeclare props each time. See https://www.tildedave.com/2014/11/15/introduction-to-contexts-in-react-js.html


So in my answer there are 3 different ways to redirect programmatically to a route. Some of the solutions has been presented already but the following ones focused only for functional components with an additional demo application.

Using the following versions:

react: 16.13.1

react-dom: 16.13.1

react-router: 5.2.0

react-router-dom: 5.2.0

typescript: 3.7.2

Configuration:

So first of all the solution is using HashRouter, configured as follows:

<HashRouter>
    // ... buttons for redirect

    <Switch>
      <Route exact path="/(|home)" children={Home} />
      <Route exact path="/usehistory" children={UseHistoryResult} />
      <Route exact path="/withrouter" children={WithRouterResult} />
      <Route exact path="/redirectpush" children={RedirectPushResult} />
      <Route children={Home} />
    </Switch>
</HashRouter>

From the documentation about <HashRouter>:

A <Router> that uses the hash portion of the URL (i.e. window.location.hash) to keep your UI in sync with the URL.

Solutions:

  1. Using <Redirect> to push using useState:

Using in a functional component (RedirectPushAction component from my repository) we can use useState to handle redirect. Tricky part is once the redirection happened we need to set the redirect state back to false. By using setTimeOut with 0 delay we are waiting until React commits Redirect to the DOM then getting back the button in order to use next time.

Please find my example below:

const [redirect, setRedirect] = useState(false);
const handleRedirect = useCallback(() => {
    let render = null;
    if (redirect) {
        render = <Redirect to="/redirectpush" push={true} />
        
        // in order wait until commiting to the DOM
        // and get back the button for clicking next time
        setTimeout(() => setRedirect(false), 0);
    }
    return render;
}, [redirect]);

return <>
    {handleRedirect()}
    <button onClick={() => setRedirect(true)}>
        Redirect push
    </button>
</>

From <Redirect> documentation:

Rendering a <Redirect> will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.

  1. Using useHistory hook:

In my solution there is a component called UseHistoryAction which represents the following:

let history = useHistory();

return <button onClick={() => { history.push('/usehistory') }}>
    useHistory redirect
</button>

The useHistory hook gives us access to the history object which helps us programmatically navigate or change routes.

  1. Using withRouter, get the history from props:

Created one component called WithRouterAction, displays as below:

const WithRouterAction = (props:any) => {
    const { history } = props;

    return <button onClick={() => { history.push('/withrouter') }}>
        withRouter redirect
    </button>
}

export default withRouter(WithRouterAction);

Reading from withRouter documentation:

You can get access to the history object's properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

Demo:

For better representation I have built a GitHub repository with these examples, please find it below:

https://github.com/norbitrial/react-router-programmatically-redirect-examples

I hope this helps!


Try hookrouter instead, "the modern alternative to react-router"

https://www.npmjs.com/package/hookrouter

import { useRoutes, usePath, A} from "hookrouter";

to answer OP question about linking through select box you can do it:

navigate('/about');

*** UPDATED ANSWER ***

I think hook-router was a good starter kit and helped me learn about routing but have since updated to react-router for it's history and query parameter handling.

import { useLocation, useHistory } from 'react-router-dom';


const Component = (props) => {
    const history = useHistory();
    
    // Programmatically navigate
    history.push(newUrlString);
}

You push where you want to navigate into the location.history.


React-Router 4.x Answer :

On my end, I like to have a single history object that I can carry even outside components. What I like to do is 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>;
    }
}

EDIT April 16th, 2018 :

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>;
    }
}

May not be the best approach but... Using react-router v4, the following Typescript could give an idea for some.

In the rendered component below, e.g. LoginPage, router object is accessible and just call router.transitionTo('/homepage') to navigate.

Navigation code was taken from.

"react-router": "^4.0.0-2", "react": "^15.3.1",

_x000D_
_x000D_
import Router from 'react-router/BrowserRouter';_x000D_
import { History } from 'react-history/BrowserHistory';_x000D_
import createHistory from 'history/createBrowserHistory';_x000D_
const history = createHistory();_x000D_
_x000D_
interface MatchWithPropsInterface {_x000D_
  component: typeof React.Component,_x000D_
  router: Router,_x000D_
  history: History,_x000D_
  exactly?: any,_x000D_
  pattern: string_x000D_
}_x000D_
_x000D_
class MatchWithProps extends React.Component<MatchWithPropsInterface,any> {_x000D_
  render() {_x000D_
    return(_x000D_
      <Match {...this.props} render={(matchProps) => (_x000D_
             React.createElement(this.props.component, this.props)_x000D_
_x000D_
        )}_x000D_
       />_x000D_
    )_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
    <Router>_x000D_
      {({ router }) => (_x000D_
        <div>_x000D_
          <MatchWithProps exactly pattern="/" component={LoginPage} router={router} history={history} />_x000D_
          <MatchWithProps pattern="/login" component={LoginPage} router={router} history={history} />_x000D_
          <MatchWithProps pattern="/homepage" component={HomePage} router={router} history={history} />_x000D_
          <Miss component={NotFoundView} />_x000D_
        </div>_x000D_
      )}_x000D_
    </Router>,_x000D_
_x000D_
   document.getElementById('app')_x000D_
);
_x000D_
_x000D_
_x000D_


If happen to pair RR4 w/ redux through react-router-redux, use the routing action creators from react-router-redux is a option as well.

import { push, replace, ... } from 'react-router-redux'

class WrappedComponent extends React.Component {
  handleRedirect(url, replaceState = true) { 
    replaceState 
      ? this.props.dispatch(replace(url)) 
      : this.props.dispatch(push(url)) 
  }
  render() { ... }
}

export default connect(null)(WrappedComponent)

If use redux thunk/saga to manage async flow, import the above action creators in redux actions and hook to react components using mapDispatchToProps might be better.


Update : React Router v6 with hooks

import {useNavigate} from 'react-router-dom';
let navigate = useNavigate();
navigate('home');

And to move across the browser history,

navigate(-1); ---> Go back
navigate(1);  ---> Go forward
navigate(-2); ---> Move two steps backward.

The right answer was for me at the time of writing

this.context.router.history.push('/');

But you need to add PropTypes to your component

Header.contextTypes = {
  router: PropTypes.object.isRequired
}
export default Header;

Don't forget to import PropTypes

import PropTypes from 'prop-types';

Maybe not the best solution but it gets the job done:

import { Link } from 'react-router-dom';

// create functional component Post
export default Post = () => (
    <div className="component post">

        <button className="button delete-post" onClick={() => {
            // ... delete post
            // then redirect, without page reload, by triggering a hidden Link
            document.querySelector('.trigger.go-home').click();
        }}>Delete Post</button>

        <Link to="/" className="trigger go-home hidden"></Link>

    </div>
);

Basically, a logic tied to one action (in this case a post deletion) will end up calling a trigger for redirect. This is not ideal because you will add a DOM node 'trigger' to your markup just so you can conveniently call it when needed. Also, you will directly interact with the DOM, which in a React component may not be desired.

Still, this type of redirect is not required that often. So one or two extra, hidden links in your component markup would not hurt that much, especially if you give them meaningful names.


React-Router V4

if you're using version 4 then you can use my library (Shameless plug) where you simply dispatch an action and everything just works!

dispatch(navigateTo("/aboutUs"));

trippler


In react router v4. I follow this two way to route programmatically.

1. this.props.history.push("/something/something")
2. this.props.history.replace("/something/something")

Number two

Replaces the current entry on the history stack

To get history in props you may have to wrap your component with

withRouter


With the current React version (15.3), this.props.history.push('/location'); worked for me, but it showed the following warning:

browser.js:49 Warning: [react-router] props.history and context.history are deprecated. Please use context.router.

and I solved it using context.router like this:

import React from 'react';

class MyComponent extends React.Component {

    constructor(props) {
        super(props);
        this.backPressed = this.backPressed.bind(this);
    }

    backPressed() {
        this.context.router.push('/back-location');
    }

    ...
}

MyComponent.contextTypes = {
    router: React.PropTypes.object.isRequired
};

export default MyComponent;

To use withRouter with a class-based component, try something like this below. Don't forget to change the export statement to use withRouter:

import { withRouter } from 'react-router-dom'

class YourClass extends React.Component {
  yourFunction = () => {
    doSomeAsyncAction(() =>
      this.props.history.push('/other_location')
    )
  }

  render() {
    return (
      <div>
        <Form onSubmit={ this.yourFunction } />
      </div>
    )
  }
}

export default withRouter(YourClass);

Programmatically navigate in Class-based components.

import { Redirect } from "react-router-dom";

class MyComponent extends React.Component{
    state= {rpath: null}

    const goTo= (path)=> this.setState({rpath: path});

    render(){
        if(this.state.rpath){
            return <Redirect to={this.state.rpath}/>
        }
        .....
        .....
    }
}

Hope, It helps.


Using the "useHistory" hook is the best option if you're using a newer version of react


For this one, who does not control the server side and because of this is using hash router v2:

Place your history into separate file (e.g. app_history.js ES6):

import { useRouterHistory } from 'react-router'
import { createHashHistory } from 'history'
const appHistory = useRouterHistory(createHashHistory)({ queryKey: false });

export default appHistory;

And use it everywhere!

Your entry point for react-router (app.js ES6):

import React from 'react'
import { render } from 'react-dom'
import { Router, Route, Redirect } from 'react-router'
import appHistory from './app_history'
...
const render((
  <Router history={appHistory}>
  ...
  </Router>
), document.querySelector('[data-role="app"]'));

Your navigation inside any component (ES6):

import appHistory from '../app_history'
...
ajaxLogin('/login', (err, data) => {
  if (err) {
    console.error(err); // login failed
  } else {
    // logged in
    appHistory.replace('/dashboard'); // or .push() if you don't need .replace()
  }
})

Simply just use this.props.history.push('/where/to/go');


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
}

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.


Those who are facing issues in implementing this on react-router v4.

Here is a working solution for navigating through the react app from redux actions.

history.js

import createHistory from 'history/createBrowserHistory'

export default createHistory()

App.js/Route.jsx

import { Router, Route } from 'react-router-dom'
import history from './history'
...
<Router history={history}>
 <Route path="/test" component={Test}/>
</Router>

another_file.js OR redux file

import history from './history' 

history.push('/test') // this should change the url and re-render Test component

All thanks to this comment: ReactTraining issues comment


with React-Router v4 on the horizon, there is now a new way of doing this.

import { MemoryRouter, BrowserRouter } from 'react-router';

const navigator = global && global.navigator && global.navigator.userAgent;
const hasWindow = typeof window !== 'undefined';
const isBrowser = typeof navigator !== 'undefined' && navigator.indexOf('Node.js') === -1;
const Router = isBrowser ? BrowserRouter : MemoryRouter;

<Router location="/page-to-go-to"/>

react-lego is an example app that shows how to use/update react-router and it includes example functional tests which navigate the app.


This worked for me, no special imports needed:

<input 
  type="button" 
  name="back" 
  id="back" 
  class="btn btn-primary" 
  value="Back" 
  onClick={() => { this.props.history.goBack() }} 
/>

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to react-router

React : difference between <Route exact path="/" /> and <Route path="/" /> You should not use <Link> outside a <Router> React Router Pass Param to Component Detect Route Change with react-router What is the best way to redirect a page using React Router? No restricted globals React-router v4 this.props.history.push(...) not working How to pass params with history.push/Link/Redirect in react-router v4? How to use Redirect in the new react-router-dom of Reactjs How to implement authenticated routes in React Router 4?