How to Protected Routes and Authentication in ReactJS | Complete guide on React Router authentication | What are Protected Routes in React JS

474 views

Not every page should be open to the public in practical applications. Certain pages, such as the admin panel, settings, or user dashboard, ought to be available only once the user logs in. This is where ReactJS’s protected routes are useful.

Components known as protected routes limit access according to authentication status. This article will teach you how to use React Router to restrict routes and build a simple authentication system. State will be used to mimic the login status, and access will be managed via a new wrapper component called PrivateRoute.

When connecting login systems with Firebase, JWT, or bespoke auth APIs, this method is crucial.

โœ… Example: Basic Protected Route Setup

๐Ÿงฉ App.js

  1.    import React, { useState } FROM 'react';
  2. import { BrowserRouter, Routes, Route, Navigate } FROM 'react-router-dom';
  3. import Home FROM './Home';
  4. import Dashboard FROM './Dashboard';
  5.  
  6. FUNCTION PrivateRoute({ isAuthenticated, children }) {
  7.   RETURN isAuthenticated ? children : <Navigate TO="/" />;
  8. }
  9.  
  10. FUNCTION App() {
  11.   const [isAuthenticated, setIsAuthenticated] = useState(FALSE);
  12.  
  13.   RETURN (
  14.     <BrowserRouter>
  15.       <Routes>
  16.         <Route path="/" element={<Home onLogin={() => setIsAuthenticated(TRUE)} />} />
  17.         <Route
  18.           path="/dashboard"
  19.           element={
  20.             <PrivateRoute isAuthenticated={isAuthenticated}>
  21.               <Dashboard />
  22.             </PrivateRoute>
  23.           }
  24.         />
  25.       </Routes>
  26.     </BrowserRouter>
  27.   );
  28. }
  29.  
  30. export DEFAULT App;

 

๐Ÿงฉ Home.js

  1.   import React FROM 'react';
  2. import { useNavigate } FROM 'react-router-dom';
  3.  
  4. FUNCTION Home({ onLogin }) {
  5.   const navigate = useNavigate();
  6.  
  7.   const handleLogin = () => {
  8.     onLogin(); // Simulate login
  9.     navigate('/dashboard');
  10.   };
  11.  
  12.   RETURN (
  13.     <div STYLE={{ padding: '20px' }}>
  14.       <h2>Welcome TO the Home Page</h2>
  15.       <button onClick={handleLogin}>Login & GO TO Dashboard</button>
  16.     </div>
  17.   );
  18. }
  19.  
  20. export DEFAULT Home;

 

๐Ÿงฉ Dashboard.js

  1.   import React FROM 'react';
  2.  
  3. FUNCTION Dashboard() {
  4.   RETURN <h2>๐Ÿ”’ Welcome TO the Protected Dashboard</h2>;
  5. }
  6.  
  7. export DEFAULT Dashboard;

๐Ÿง  Summary

Only authorized users can access sensitive pages thanks to ReactJS’s protected routes. Building authentication flows for contemporary apps is simple with React Router’s Navigate and a PrivateRoute wrapper. Connect this to Firebase auth logic or JWT tokens for practical applications.

 

FAQ (Frequently Asked Questions)

Is the React Router secure?

React Router provides a straightforward way to handle routing in your application, and by combining it with authentication logic, you can create a secure environment for your users. In this tutorial, we'll explore how to implement secure routing in React. js using React Router and authentication logic.

What is the best way to handle authentication in React?

The best practice for React authentication is to take advantage of powerful encryption algorithms that offer a strong level of protection and use multi-factor authentication whenever possible.

What is useState and useEffect in React JS?

useState is a hook used to manage state in functional components, while useEffect is a hook used to manage side effects (like fetching data, setting up event listeners, or updating the DOM) in functional components.

๐Ÿ‘‰ Get Complementary โ†’

right side banner -- www.w3webmart.com
 
  
๐Ÿ‘‰ Get Free Course โ†’

๐Ÿ“Œ Salesforce Administrators

๐Ÿ“Œ Salesforce Lightning Flow Builder

๐Ÿ“Œ Salesforce Record Trigger Flow Builder

๐Ÿ‘‰ Get Free Course โ†’

๐Ÿ“Œ Aura Lightning Framework

๐Ÿ“Œ Lightning Web Component (LWC)

๐Ÿ“Œ Rest APIs Integration



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net