How to Create a Private or Protected Route in React JS

How to create a Private or Protected Route in React JS

Here are the steps –

1.  Create a component “PrivateRoute.jsx”

import {useSelector} from ‘react-redux’
import {Navigate, Outlet, } from ‘react-router-dom’
const PrivateRoute = () => {
    const {currentUser}=useSelector((state)=>state.user)
  return currentUser ? <Outlet/> : <Navigate to=‘/signin’/>
}
export default PrivateRoute
 
2. Add These in App.jsx –
        <Route element={<PrivateRoute/>}>
        <Route path=‘/dashboard’ element={<Dashboard/>}/>
        </Route>
 
 
Video Tutorial: