React JS Tutorial - Programmatic Redirects
In this tutorial, we will learn about Programmatic Redirects in React Router. The History Library plays a crucial role in React Router, providing three essential components: location, match, and history.
The history component, which comes from the History library, has several useful properties related to routing. One of the most important properties is history.push
, which allows us to insert new entries into the history stack, effectively redirecting the user to another path.
Implementing Programmatic Redirects
Now, let's see how we can implement programmatic redirects in our React application. Switch to your project and open the Navbar.js file.
First, import the withRouter
component:
import {withRouter} from 'react-router-dom';
Next, add a setTimeout
function inside the render method:
render(){
setTimeout(()=>{
this.props.history.push('/contact');
},3000);
}
This will automatically redirect the user to the Contact component after 3 seconds.
Testing the Redirect
Let's test the redirect. Switch to your browser and click on the Home link. The page will redirect to the Contact component after 3 seconds.
As you can see, the Home component is displayed initially, and then it automatically redirects to the Contact page after 3 seconds.
In this way, you can programmatically redirect users in your React application using the history.push
method.