How to Create a Protected Route with react-router-dom?
Last Updated :
31 May, 2024
A protected route in a React application is a route that only authorized users can access. This is useful for securing parts of an application that should not be available to everyone. We will see how we can create a protected route with react-router-dom.
Prerequisites:
Steps to Setup ReactJS Application and Installing Required Modules
Step 1: Create a ReactJS application using the following command
npx create-react-app my-app
Step 2: Navigate to the Project directory
cd my-app
Step 3: Install the necessary packages/libraries in your project using the following commands
npm install react-router-dom
Project Structure:
Project StructureThe updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.3",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Approach to Create a Protected Route
- Create an isAuthenticated state in the App component to track whether the user is logged in.
- Inside the ProtectedRoute component in the App, add Route elements for its child components we want to keep protected.
- Create a ProtectedRoute component that checks if the user is authenticated.
- When a user is authenticated we will render the child routes using <Outlet /.> otherwise redirect the user to the login page using <Navigate to/>.
- Create LoginPage where we will perform a simple hardcoded check for credentials.
- If the credentials are correct, we call the login function and navigate the user to the Dashboard page using useNavigate.
Example: In this example, we have created a protected dashboard route which will be accessible only if the user is authenticated.
JavaScript
// App.js
import React, { useState, useEffect } from 'react';
import { Route, Routes } from 'react-router-dom';
import { BrowserRouter } from 'react-router-dom'
import Dashboard from './components/Dashboard';
import ProtectedRoute from './components/ProtectedRoute';
import LoginPage from './components/LoginPage';
const App = () => {
const [isAuthenticated, setIsAuthenticated] =
useState(false);
const login = () => {
setIsAuthenticated(true);
};
const logout = () => {
setIsAuthenticated(false);
};
return (
<BrowserRouter>
<Routes>
<Route element={<ProtectedRoute isAuthenticated
={isAuthenticated} />} >
<Route path="dashboard"
element={<Dashboard logout
={logout} />} />
</Route>
<Route path="/"
element={<LoginPage login
={login} />} />
</Routes>
</BrowserRouter>
);
};
export default App;
JavaScript
// ProtectedRoute.js
import React from 'react'
import { Navigate, Outlet } from 'react-router-dom'
const ProtectedRoute = (props) => {
// let auth={'token': false}
return (
props.isAuthenticated ?
<Outlet /> : <Navigate to="/" />
)
}
export default ProtectedRoute;
JavaScript
// LoginPage.js
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
const LoginPage = ({ login }) => {
const [userId, setUserId] = useState('');
const [pass, setPass] = useState('');
const navigate = useNavigate();
const handleLogin = () => {
if (userId === 'user' && pass === 'pass') {
login(userId, pass);
navigate('/dashboard');
}
};
return (
<div>
<h2>Login Page</h2>
<div>
<input
type="text"
placeholder="User ID"
value={userId}
onChange={(e) =>
setUserId(e.target.value)}
/>
</div>
<div>
<input
type="text"
placeholder="Password"
value={pass}
onChange={(e) =>
setPass(e.target.value)}
/>
</div>
<button onClick={handleLogin}>Login</button>
</div>
);
};
export default LoginPage;
JavaScript
// Dashboard.js
import React from 'react';
import { useNavigate } from 'react-router-dom';
const Dashboard = ({ logout }) => {
const navigate = useNavigate();
const handleLogout = () => {
logout();
navigate('/');
};
return (
<div>
<h2>Hello user welcome to Dashboard</h2>
<h3>This page is protected</h3><br />
<button onClick={handleLogout}>
Logout
</button>
</div>
);
};
export default Dashboard;
Step to Run Application: Run the application using the following command from the root directory of the project
npm start
Output:
Output
Similar Reads
How to Create Custom Router with the help of React Router ? To create a custom Router using React Router, you can define a new component that utilizes the Router's 'BrowserRouter' along with 'Route' components to handle different paths and render corresponding components. Use 'Link' components for navigation within your application, providing a seamless rout
3 min read
How to Integrate React Router with Remix? Integrating React Router with Remix includes the usage of Remix's integrated router abilities thinking that Remix already uses React Router as its foundation. However, if you want to go beyond number one routing and leverage several React Router's extra precise or advanced skills.You may integrate t
7 min read
What are Protected Routes in React JS ? In web development, security is critical when building React applications, especially those handling sensitive data or functionalities, it's crucial to restrict access to certain parts of the application to authorized users only. This is where protected routes come into play. In this article, we wil
4 min read
How to handle Nested Routes in React Router ? React Router allows us to create a hierarchical structure where child components can be rendered within parent components, resulting in a seamless navigation flow. In this article, we will see how to handle nested Routes in React Router. Approach to handle Nested RoutesTo implement nested routes in
3 min read
React Router vs. React Router DOM Routing is a fundamental part of any web application. It allows users to move between pages or views. smoothly in traditional web development Routing involves mapping URLs to specific content or views on the server. These are the following topics that we are going to discuss: Table of ContentWhat is
4 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