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('/');
});
};
}