How to push to History in React Router v4?

Chris :

In the current version of React Router (v3) I can accept a server response and use browserHistory.push to go to the appropriate response page. However, this isn't available in v4, and I'm not sure what the appropriate way to handle this is.

In this example, using Redux, components/app-product-form.js calls this.props.addProduct(props) when a user submits the form. When the server returns a success, the user is taken to the Cart page.

// actions/index.js
export function addProduct(props) {
  return dispatch =>
    axios.post(`${ROOT_URL}/cart`, props, config)
      .then(response => {
        dispatch({ type: types.AUTH_USER });
        localStorage.setItem('token', response.data.token);
        browserHistory.push('/cart'); // no longer in React Router V4
      });
}

How can I make a redirect to the Cart page from function for React Router v4?

Oleg Belostotsky :

You can use the history methods outside of your components. Try by the following way.

First, create a history object used the history package:

// src/history.js

import { createBrowserHistory } from 'history';

export default createBrowserHistory();

Then wrap it in <Router> (please note, you should use import { Router } instead of import { BrowserRouter as Router }):

// src/index.jsx

// ...
import { Router, Route, Link } from 'react-router-dom';
import history from './history';

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/login">Login</Link></li>
        </ul>
        <Route exact path="/" component={HomePage} />
        <Route path="/login" component={LoginPage} />
      </div>
    </Router>
  </Provider>,
  document.getElementById('root'),
);

Change your current location from any place, for example:

// src/actions/userActionCreators.js

// ...
import history from '../history';

export function login(credentials) {
  return function (dispatch) {
    return loginRemotely(credentials)
      .then((response) => {
        // ...
        history.push('/');
      });
  };
}

UPD: You can also see a slightly different example in React Router FAQ.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

react-router (v4) how to go back?

Use history.push in action creator with react-router-v4?

React Router v4 - How to get current route?

How to listen to route changes in react router v4?

How to get history on react-router v4?

How to get query parameters in react-router v4

How to parse query string in react-router v4

How to nest routes in React Router v4?

How to access history object outside <Route /> in React Router v4

How do I pass props in react router v4?

how to access history object in new React Router v4

How to use React's Router v4 history.push()

React Router v4 baseName and custom history

React router v4 broswer history not working with code splitting

React Router BrowserRouter History Push & Google Analytics

How to prevent history.push if location didn't change in react-router4?

React-Router v4. How to append a parameter to URL? TypeError: history.push is not a function

How to manipulate history in React Router v4?

Unsure how to implement history.push with react-router v4

React router `this.props.history.push` - history not defined

open window using react-router v4's this.props.history.push?

How to push to History in React Router v5?

How to wrap React Router v4's NavLink component?

Push history at actions react-router v4 doesn't navigate

React router history.push() not working from history.listen()

Onsubmit and history push is not working react router

How to send props to children in React Router v4?

React router push to history and preserve relative path

How to push to History in React Router v6? I face with not found message