Navigate Component in React Router
Last Updated :
23 Jul, 2025
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
import {BrowserRouter, Routers, Route} from "react-router-dom"
import Home from "./components/Home"
import Login from "./components/Login"
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={ <Home />} />
<Route path="/login" element = { <Login/> } />
// other routes
</Routes>
</BrowserRouter>
)
}
export default App;
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
// src/App.js
import { Route, Routes } from "react-router-dom";
import Home from "./components/Home";
import Login from "./components/Login";
function App() {
return (
<div className="App">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
</Routes>
</div>
);
}
export default App;
JavaScript
// src/components/Home.jsx
import React from "react";
const Home = () => {
return (
<div>
<h1>Home</h1>
</div>
);
};
export default Home;
JavaScript
// src/components/Login.jsx
import React, { useState } from "react";
import { Navigate } from "react-router-dom";
const Login = () => {
const [loginDetails, setLoginDetails] = useState({
email: "",
password: ""
});
const [user, setUser] = useState(null);
const handleChange = (e) => {
const { name, value } = e.target;
setLoginDetails((loginDetails) => ({
...loginDetails,
[name]: value
}));
};
const handleSubmit = (e) => {
e.preventDefault();
setUser(loginDetails);
};
return (
<div>
<form>
<label>
Email:
<input
type="email"
name="email"
value={loginDetails.email}
onChange={handleChange}
required
/>
</label>
<label>
Password:
<input
type="password"
name="password"
value={loginDetails.password}
onChange={handleChange}
required
/>
</label>
<button type="submit" onClick={handleSubmit}>
Login
</button>
</form>
{
user &&
<Navigate to="/" state={user} replace={true} />
}
</div>
);
};
export default Login;
Output
Live Display of NavigationIn 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.
JavaScript
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
Navigate Component in React RouterIn 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.
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
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import RegistrationForm from "./RegistrationForm";
import ThankYouPage from "./ThankYouPage";
import "./styles.css";
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<RegistrationForm />} />
<Route path="/thank-you" element={<ThankYouPage />} />
</Routes>
</Router>
);
}
export default App;
RegistrationForm.js
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
function RegistrationForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const navigate = useNavigate();
const handleSubmit = (e) => {
e.preventDefault();
setTimeout(() => {
console.log('Form submitted:', { name, email });
navigate('/thank-you');
}, 1000);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>Name:</label>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
</div>
<div>
<label>Email:</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<button type="submit">Submit</button>
</form>
);
}
export default RegistrationForm;
ThankYouPage.js
function ThankYouPage() {
return <h2>Thank you for registering!</h2>;
}
export default ThankYouPage;
Output
Navigate Component in React RouterIn 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
import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
function DelayedRedirect() {
const navigate = useNavigate();
useEffect(() => {
const timer = setTimeout(() => {
navigate('/thank-you');
}, 3000);
return () => clearTimeout(timer);
}, [navigate]);
return (
<div>
<h2>Redirecting you in 3 seconds...</h2>
</div>
);
}
export default DelayedRedirect;
ThankYouPage.js
function ThankYouPage() {
return <h2>Thank you for your patience!</h2>;
}
export default ThankYouPage;
Output
Navigate Component in React RouterIn 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.
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. Why Use React?Before React, web development faced issues like slow DOM updates and mes
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides methods to interact with the Document Object Model, or DOM. This package allows developers to access and modify the DOM. It is a package in React that provides DOM-specific methods that can be used at the top level of a web app to enable an efficient wa
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.Stateless (before hooks)
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects