How can I use React Router v4 to programmatically push to history

0 votes
With the help of proper code example can you tell me How can I use React Router v4 to programmatically push to history?
Feb 12 in Node-js by Ashutosh
• 20,830 points
92 views

1 answer to this question.

0 votes

You can utilize the history object's push method. Here's how to implement it:

Create a History Object:

First, create a custom history object using the history package.

// history.js

import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

export default history;


Integrate History with Router:

Use the Router component from react-router-dom and pass the custom history object to it.

// index.js

import React from 'react';

import ReactDOM from 'react-dom';

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

import history from './history';

ReactDOM.render(

  <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>,

  document.getElementById('root')

);


Programmatically Navigate:


Within your components or action creators, you can now use the history.push method to navigate to different routes.

// userActionCreators.js

import history from './history';

export function login(credentials) {

  return function (dispatch) {

    return loginRemotely(credentials)

      .then((response) => {

        // ...

        history.push('/');

      });

  };

}

answered Feb 21 by Kavya

Related Questions In Node-js

0 votes
1 answer
0 votes
1 answer

How can I use all the React events with Material-UI components?

The best approach is to leverage the ...READ MORE

answered Feb 22 in Node-js by Kavya
40 views
0 votes
1 answer
0 votes
1 answer

How can I use an http proxy with node.js http.Client?

Hello @kartik, You can use request, I just found ...READ MORE

answered Jul 17, 2020 in Node-js by Niroj
• 82,840 points
10,788 views
0 votes
1 answer

How can query string parameters be retrieved in JavaScript?

You can retrieve query string parameters from ...READ MORE

answered Feb 21 in Node-js by Kavya
49 views
0 votes
1 answer
0 votes
1 answer

What is the difference between calling "super()" and "super(props)" in React ES6 classes?

Aspect super() super(props) Purpose Calls the parent class constructor without passing ...READ MORE

answered Feb 21 in Node-js by Kavya
61 views
0 votes
1 answer
0 votes
1 answer

How can props be passed using Link in React Router?

In React Router, you can pass data ...READ MORE

answered Feb 21 in Node-js by kavya
57 views
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP