Redirect to Another Page in ReactJS



Redirecting is one of the vital features in frontend applications like React apps. Moving from one page to another is known as navigation. In React, navigation is important for maintaining a Single Page Application for a better user experience. react-router-dom is a npm package which enables dynamic routing in react application. In this article, we are going to learn how we can redirect from one page to another in ReactJS.

Using React Router Dom

Navigating to another page can be done efficiently with the help of react-router-dom. It is an npm package responsible for client-side navigation. Using React Router Dom, we can easily navigate the user to a different URL without refreshing the browser, meaning without making any additional requests to the server. React Router is a collection of React components and utilities that makes dynamic routing easy.

Steps to Redirect to Another Page

Here's the step-by-step guide on how to redirect the user to another page in React -

1. Create react app

There are multiple ways to create a React app. Vite is used here because of its fast build times and modern features. Alternatively, you can also use npx create-react-app, which provides a pre-configured Webpack setup.

npm create vite@latest <my-app>

2. Install the dependencies

npm install react-router-dom

Folder Structure

After creating react app, folder structure of project will be like this.


3. Files Overview

Here are the files of project which will help us to understand the how navigation works. If you initialized the project using 'npx create-react-app <my-app>' then consider main.jsx as index.js file.

In main.jsx file, we need to wrap everything inside <BrowswerRouter> for enabling client-side routing in the application.

Example

// main.jsx

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import {BrowserRouter} from 'react-router-dom'

import './index.css'
import App from './App.jsx'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </StrictMode>,
)

In App.jsx file, we can map components to specific routes using the <Route> and the <Routes>. This allows the application to navigate between different pages seamlessly based on the URL path. Route is used to define the route and the component which you want to serve.

  • <Route>: In <Route>, path attribute is used to define a specific path of route and element attribute ensures that the specified component is rendered for that route.
    <Route path="/home" element={<Home />} />
  • <Routes>: This is the container in which we define all the routes. It ensures that only the first matching route is rendered.
  • <Link>: <Link> component allows users to navigate to different routes without reloading the page. In Link component, to attribute is used to define the path on which we want to navigate without reloading the page.
    <Link to="/home">Home</Link>

    Note : To avoid reloading, make sure to use the <Link> tag instead of the <a> tag.

How to Implement Routing in React

Here is an example of how to implement routing in React:

// App.jsx

import React from 'react'
import {Routes, Route, Link, Navigate} from 'react-router-dom'

const Home = () => <div>This is Home Page</div>;
const About = () => <div>This is About Page</div>;
const Profile = () => <div>This is About Page.</div>;

const App = () => {
  return (
    <>
      {/* Navigation Menu */}
      <nav>
        <ul>
          <li><Link to="/home">Home</Link></li>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/profile">Profile</Link></li>
        </ul>
      </nav>

      {/* Define Routes */}
      <Routes>
        <Route path='/home' element={ <Home/> } />
        <Route path='/about' element={ <About/> } />
        <Route path='/profile' element={ <Profile/> } />
        
        {/* Redirect unknown paths to Home */}
        <Route path='*' element={<Navigate to='/home' />} />
      </Routes>
    </>
  )
}

export default App

Run the following command to start the application -

npm run dev     # for vite-app
npm start       # for react-app

Output

This is the output in browser. When any undefined route is hit, it will navigate to home route.

Conclusion

In this article, we explained the step-by-step procedure of how one can redirect the user to another page in React.

Updated on: 2024-12-19T09:38:16+05:30

150 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements