How to automatically redirect to the next page after n seconds in ReactJS?

·

2 min read

How to automatically redirect to the next page after n seconds in ReactJS?

Introduction

In this blog, we will see how to automatically redirect to the next page after 2 seconds using the ReactJS module react-router-dom. So, let's jump into it.

Install React App

Install the React app using the usual command npx create-react-app page-redirect-app . Check out my blogs to learn more about installing the React app.

Install React-router-dom

Install the react-router-dom dependency using the command npm install react-router-dom

Create Pages

In this blog, we are going to create two pages: a welcome page and a home page.

So, create pages folder in the src folder and create two files, namely WelcomePage.jsx and Homepage.jsx

Write a simple code inside the welcome and home page

// WelcomePage.jsx
import React from 'react';

function WelcomePage() {
  return (
    <div>
      Welcome to my Site!
    </div>
  )
}

export default WelcomePage
// HomePage.jsx
import React from 'react';

function HomePage() {
  return (
    <div>
      Welcome to Home Page
    </div>
  )
}

export default HomePage

Routing

In this section, we will see how to route WelcomePage to / path and HomePage to /home path in App.js

// App.js
import './App.css';
import WelcomePage from './pages/WelcomePage'; // Welcome Page import
import HomePage from './pages/HomePage'; // Home Page import
import {
  BrowserRouter as Router,
  Routes,
  Route
} from 'react-router-dom'; // Importing the necessary function from react-router-dom

function App() {
  return (
    <Router>
      <Routes>
        <Route path='/' Component={WelcomePage}/>{/* Routed the welcome page to / path */}
        <Route path='/home' Component={HomePage}/> {/* Routed the home page to /home path */}
      </Routes>
    </Router>
  );
}

export default App;

Update Welcome page

Update the welcome page so that it will redirect automatically after 2 seconds.

// Updated WelcomePage.jsx
import React, {useEffect} from 'react';
import {useNavigate} from 'react-router-dom';

function WelcomePage() {
  const navigate = useNavigate() // Usenavigate to redirect to the page

  useEffect(() => { // UseEffect is used to set the condition for redirection
    setTimeout(() => { // Set the timeout
      navigate('/home') // Redirect path to '/home'
    }, 2000) // set time 2000ms which is equal to 2seconds
  }, [])
  return (
    <div>
      <h1>Welcome to my Site!</h1>
    </div>
  )
}

export default WelcomePage

Run the App

To run the react app, use the command npm start in the terminal

Conclusion

Hurray 🥳! We have successfully learned how to redirect to the next page automatically after 2 seconds.

Resources

GitHub Repo Link