I want to load a componente if a valid jwt exists, otherwise it should redirect to login, the redirect works but if I have a valid token the private component can not be loaded. is undefined
index.js
import React, { lazy, Suspense } from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import jwtCheck from "./utils/jwtCheck"; // <-- return true/false
import Loader from "./Loader";
const App = lazy(() => import("./App/App"));
const Login = lazy(() => import("./Login/Login"));
const root = ReactDOM.createRoot(document.getElementById("app"));
function PrivRoute({ child }) {
console.log("child:", child); // <-- "child: undefined"
return jwtCheck() ? child : <Navigate to="/login" />;
}
root.render(
<React.StrictMode>
<BrowserRouter>
<Suspense fallback={<Loader />}>
<Routes>
<Route
path="/"
element={
<PrivRoute>
<App />
</PrivRoute>
}
/>
<Route path="/login" element={<Login />} />
</Routes>
</Suspense>
</BrowserRouter>
</React.StrictMode>
);
Why is this so, can someone please help me. (is my first "real" project with react)
2
Answers
try to change chid to children in
PrivRoute
:The child of a component is found under the prop
children
not child.updated code: