0

I am creating an admin app where i want make a protected route for admin dashboard. Signin and Signup routes are public. Before creating a protected route every route was working well. I created a higher order component to create a private route. I replaced the route as Private route and the page loads and terminal gives no error. But the page renders nothing and console throws error as private route is not a route component. All children of routes must be route or react.fragment.

Here is my app.tsx file

import React from 'react';
import { BrowserRouter as Router, Navigate, Route, Routes } from 'react-router-dom';
import {Home, Signup, Signin} from './container/index';
import './App.css';
import PrivateRoute from './components/common/HOC/Index';


function App() {
  return (
    <div className="App">
      <Router>
        <Routes>
          <PrivateRoute path="/" element={<Home/>} />
          <Route path="/signup" element={<Signup />} />
          <Route path="/signin" element={<Signin />} />
        </Routes>
      </Router>
    </div>
  );
}

export default App;

Here is my private router component.

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


const PrivateRoute = (props:any) => {
    return <Route {...props}/>
}


export default PrivateRoute;
niteshraj
  • 23
  • 1
  • 9
  • react-router v6 is very much different than v5, your code should work in v5, but v6 might ask you to do things differently. Maybe this help https://dev.to/iamandrewluca/private-route-in-react-router-v6-lg5 or https://stackoverflow.com/questions/62384395/protected-route-with-react-router-v6 – Doppio Jan 06 '22 at 15:26

1 Answers1

0

PrivateRoute Component:

import React from 'react'
import { Outlet, Navigate } from 'react-router-dom'



export default function PrivateRoutes() {
    let  userid = localStorage.getItem("token") == null ? false : true;
    return (
        <>
            {userid ? <Outlet  /> : <Navigate to="/signin" />};
        </>

    )
}

App.js

import './App.css';
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import Home from './container/Home/Home'
import Signin from './container/Signin/Signin'
import Signup from './container/Signup/Signup'
import PrivateRoute from './components/HOC/privateRoute'
function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <Routes>
        <Route exact element={<PrivateRoute  />}>
            <Route exact path="/" element={<Home />} />
          </Route>
          <Route path='/signin' element={<Signin />} />
          <Route path='/signup' element={<Signup />} />
          <Route />
        </Routes>
      </BrowserRouter>
    </div>
  );
}

export default App;
Yassin Mo
  • 347
  • 2
  • 9