Open In App

Navigate Component in React Router

Last Updated : 10 May, 2025
Comments
Improve
Suggest changes
2 Likes
Like
Report

In React applications, navigation between different pages or views is an essential part of creating dynamic user interfaces. React Router is a popular library used for handling routing and navigation. One of the key features of React Router is the Navigate component, which allows for programmatic redirection.

Setting up React Router

Before using the Navigate component in React Router, it is important to set up React Router in a React application. Setting up React Router allows us to handle routing and navigation seamlessly. Below are the steps to install and set up React Router in a React project.

Step 1: Install React Router

Run the following command to install React Router

npm install react-router-dom

Step 2: Set up React Router

In your App.js, import and set up the router.

JavaScript
import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter as Router } from "react-router-dom";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
    <React.StrictMode>
        <Router>
              <App />
        </Router>
    </React.StrictMode>
);
JavaScript

Using the Navigate Component

There are many built in components in React router version 6 and Navigate component is one of them. It is a wrapper for the useNavigate hook, and used to change the current location on rendering it.

Import the Navigate component to start using it

import { Navigate } from "react-router-dom";

The Navigate component takes up three props:

<Navigate to="/login" state={{credentials: []}} replace = {true} />
  • to - A required prop. It is the path to which we want to navigate
  • replace - An optional boolean prop. Setting its value to true will replace the current entry in the history stack.
  • state - An optional prop. It can be used to pass data from the component that renders Navigate.

The state can be accessed using useLocation like this

const location = useLocation();
console.log(location.state);
// The default value of location.state is null if you don't pass any data.

The props you pass to the Navigate component are the same as the arguments required by the function returned by the useNavigate hook.

Now let's understand this with the help of example:

JavaScript
// src/index.js

import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter as Router } from "react-router-dom";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
    <React.StrictMode>
        <Router>
            <App />
        </Router>
    </React.StrictMode>
);
JavaScript JavaScript JavaScript

Output

friendly-glade-CodeSandbox-GoogleChrome2024-03-2317-29-36-ezgifcom-video-to-gif-converter
Live Display of Navigation

In this example

  • src/index.js: Renders the app and enables routing with <Router>.
  • src/App.js: Defines routes for Home and Login components.
  • src/components/Home.jsx: Displays "Home" header.
  • src/components/Login.jsx: Handles form submission and redirects to Home with user data using <Navigate>.

Use Cases of Navigate Component

1. Conditional Navigation

One of the most common use cases for Navigate is to perform navigation based on certain conditions, like whether a user is logged in or not.

import React, { useState } from 'react';

function App() {
    const [isLoggedIn, setIsLoggedIn] = useState(false);

    const toggleLogin = () => {
        setIsLoggedIn(prevState => !prevState);
    };

    return (
        <div>
            {isLoggedIn ? (
                <div>
                    <h1>Welcome, User!</h1>
                    <button onClick={toggleLogin}>Logout</button>
                </div>
            ) : (
                <div>
                    <h1>Please log in</h1>
                    <button onClick={toggleLogin}>Login</button>
                </div>
            )}
        </div>
    );
}

export default App;

Output

conditional-rendering-
Navigate Component in React Router

In this example

  • When the user clicks the "Log In" button, the state loggedIn is set to true.
  • If the loggedIn state is true, the Navigate component will redirect the user to the /dashboard route automatically.

2. Redirecting After Form Submission

Another common use case is to redirect users after a form submission. Here’s an example of redirecting after submitting a form.

styles.css
body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f9;
    margin: 0;
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
  }
  
  form {
    width: 100%;
    max-width: 400px;
    padding: 20px;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  
  input[type="text"],
  input[type="email"] {
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
  }
  
  button {
    padding: 10px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
  }
  
  button:hover {
    background-color: #45a049;
  }
  
  .thank-you {
    font-size: 24px;
    color: #333;
    text-align: center;
  }
  
App.js RegistrationForm.js ThankYouPage.js

Output

conditional-rendering-1
Navigate Component in React Router

In this example

  • App.js: Defines routes for RegistrationForm and ThankYouPage.
  • RegistrationForm.js: Submits form data and redirects to ThankYouPage after 1 second.
  • ThankYouPage.js: Displays a "Thank you for registering!" message.

3.Redirect with a Delay

In some cases, it's useful to add a short delay before redirecting, such as when showing a loading spinner or a success message.

App.js
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import DelayedRedirect from './DelayedRedirect';
import ThankYouPage from './ThankYouPage';

function App() {
    return (
        <Router>
            <Routes>
                <Route path="/" element={<DelayedRedirect />} />
                <Route path="/thank-you" element={<ThankYouPage />} />
            </Routes>
        </Router>
    );
}

export default App;
DelayedRedirect.js ThankYouPage.js

Output

redirecting
Navigate Component in React Router

In this example

  • App.js: Sets up routes for DelayedRedirect and ThankYouPage.
  • DelayedRedirect.js: Redirects to ThankYouPage after 3 seconds.
  • ThankYouPage.js: Displays a "Thank you for your patience!" message.

When to Use Navigate

The Navigate component is best suited for scenarios where you need to redirect users based on conditions or automatically after some event occurs, like:

  • User authentication: Redirecting users to login if they are not authenticated.
  • After form submissions: Redirecting users after submitting a form.
  • Conditional redirects: Based on whether certain conditions are met, like user roles or permissions.

Conclusion

The Navigate component in React Router allows for easy, condition-based redirection in React applications. It’s ideal for use cases like user authentication, form submissions, and redirects with delays. By using Navigate, developers can programmatically guide users through different routes without the need for manual links.


Next Article

Similar Reads