Navigate Component in React Router
Last Updated : 10 May, 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
Link Component in React Router
React Router is a powerful library in ReactJS that is used to create SPA (single-page applications) seamlessly. One of the components of the React Router is Link. In this article, we will be seeing the working of the Link component, various props, and usage of the Link component within React Router
5 min read
Route Component in React Router
React Router is a popular library used for managing routing in React applications. At its core lies the Route component, which plays a pivotal role in defining the relationship between URLs and corresponding components. In this article, we'll delve into the intricacies of the Route component, explor
5 min read
React MUI Navigation Components
React Material-UI (MUI) is a popular library that provides a set of reusable components for building user interfaces in React applications. These components are based on Material Design, a design system developed by Google that provides guidelines for creating visually appealing, user-friendly inter
3 min read
Await Component in React Router
The <Await> component in React Router v6 is designed to handle the rendering of deferred values with automatic error handling. It is especially useful when dealing with asynchronous data fetching in components rendered by React Router routes. The <Await> component ensures that the render
5 min read
Routes Component in React Router
Routes are an integral part of React Router, facilitating the navigation and rendering of components based on URL patterns. In this article, we'll delve into the concept of routes, understanding their role in React Router, and how to define and manage routes effectively. Table of Content What are Ro
4 min read
React Native Tab Navigation Component
In this article, we are going to see how to implement Tab Navigation in react-native. For this, we are going to use createBottomTabNavigator component. It is basically used for navigation from one page to another. These days mobile apps are made up of a single screen, so create various navigation co
3 min read
Link and NavLink components in React-Router-Dom
When creating a React app, handling navigation properly is important. React Router provides two key components, Link and NavLink, to make moving between pages easy. These components work like regular <a> tags but prevent full-page reloads, making the app faster and smoother for users. What is
5 min read
ReactJS Onsen UI Navigator Component
ReactJS Onsen-UI is a popular front-end library with a set of React components that are designed to developing HTML5 hybrid and mobile web apps in a beautiful and efficient way. Navigator components are responsible for page transitioning and managing the pages of our application. We can use the foll
3 min read
React Suite Pagination Component
React Suite is a popular front-end library with a set of React components that are designed for the middle platform and back-end products. Pagination component allows the user to select a specific page from a range of pages. We can use the following approach in ReactJS to use the React Suite Paginat
3 min read
React Native Smart Components
In this article, we are going to learn about Smart components in React Native. The smart component is one of the categories of React Components so before diving into the smart components detail. A Component is one of the core building blocks of React and React-Native. The component is a block of cod
3 min read