React router redirect after action redux

With React Router 2+, wherever you dispatch the action, you can call browserHistory.push() (or hashHistory.push() if that’s what you use):

import { browserHistory } from 'react-router'

// ...
this.props.dispatch(registerStep1Success())
browserHistory.push('/registrationStep2')

You can do this from async action creators too if that is what you use.


To build on Eni Arinde previous answer's (I don't have the reputation to comment), here is how to use the store.dispatch method after an async action :

export function myAction(data) {
    return (dispatch) => {
        dispatch({
            type: ACTION_TYPE,
            data,
        }).then((response) => {
            dispatch(push('/my_url'));
        });
    };
}

The trick is to do it in the action files and not in the reducers, since reducers should not have side effects.


Have you checked out react-router-redux? This library makes it possible to sync react-router with redux.

Here is an example from the documentation of how you can implement the redirection with a push action from react-router-redux.

import { routerMiddleware, push } from 'react-router-redux'

// Apply the middleware to the store
const middleware = routerMiddleware(browserHistory)
const store = createStore(
  reducers,
  applyMiddleware(middleware)
)

// Dispatch from anywhere like normal.
store.dispatch(push('/foo'))

Simplest solution for router version 4+: We use "react-router-dom": "4.3.1" It doesn't work with version 5+

export your browser history from the place where it was initialised and use browserHistory.push('/pathToRedirect'):

Package history must be installed(example: "history": "4.7.2"):

npm install --save history

In my project I initialise browser history in index.js:

import { createBrowserHistory } from 'history';

export const browserHistory = createBrowserHistory();

Redirect in the action:

export const actionName = () => (dispatch) => {
    axios
            .post('URL', {body})
            .then(response => {
                // Process success code
                  dispatch(
                    {
                      type: ACTION_TYPE_NAME,
                      payload: payload
                    }
                  );
                }
            })
            .then(() => {
                browserHistory.push('/pathToRedirect')
            })
            .catch(err => {
                // Process error code
                    }
                );
            });
};