Member-only story

Private Route, Public Route, and Restricted Route with React Router

Sumit kumar Singh
4 min readApr 8, 2023

React Router is a popular library for handling routing in single-page applications built with React. It provides a flexible and declarative API for defining routes and rendering components based on the current URL. React Router supports three main types of routes: private routes, public routes, and restricted routes.

Private Route:

Private routes are routes that require authentication before they can be accessed. They are often used to protect sensitive content or functionality that should only be available to logged-in users. To create a private route in React Router, you can use the Route component with a render prop that checks if the user is authenticated before rendering the component.

Here is an example of a private route:

import React from 'react';
import { Route, Redirect } from 'react-router-dom';

const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
<Route
{...rest}
render={props =>
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)
}
/>
);

export default PrivateRoute;

In this example, the PrivateRoute component takes three props: component, isAuthenticated

--

--

Sumit kumar Singh
Sumit kumar Singh

Written by Sumit kumar Singh

YouTube: https://shorturl.at/8zZ4B Topmate: https://topmate.io/sumit_kr_singh 📚 HTML, Angular, React, and JavaScript 🧑‍💻 Tips & tricks

No responses yet