Rizwan17/ecommerce-admin-app

Fixed the private routes error

Closed this issue · 1 comments

Private route is not working in my app
my node version is 16.5
and npm version is 8.5

errorName: [PrivateRoute] is not a component. All component children of must be a or <React.Fragment>

Private route is not working in my app my node version is 16.5 and npm version is 8.5

errorName: [PrivateRoute] is not a component. All component children of must be a or <React.Fragment>

That is for the version of react router, the app used the Redirect component, that component was delete of react router in version 6.3 and changes for Navigate, also in that version the component Routes only accept Route components, so when you use PrivateRoute for render a Route the application throw an error.

I resolved that problem recently, this was my solution for PrivateRoute with react router 6.3:

import React from "react";
import { Route, Navigate } from "react-router-dom";

const PrivateRoute = ({ component: Component }) => {
   const token = window.localStorage.getItem("token");

   return <>{
      token ? <Component /> : <Navigate to={"/signin"} />
   }</>;
};
export default PrivateRoute;

Also in the Route i did this:

<Route path="/" exact element={<PrivateRoute component={Home} />} />

I used that sintax with all PrivateRoute and works.

See my repo of the proyect if you want...