skip to Main Content

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


  1. try to change chid to children in PrivRoute :

    function PrivRoute({ children }) {
        console.log("child:", children); // <-- "child: undefined"
        return jwtCheck() ? children : <Navigate to="/login" />;
    }
    
    Login or Signup to reply.
  2. The child of a component is found under the prop children not child.

    updated code:

    function PrivRoute({ children: child  }) {
        console.log("child:", child); // <-- "child: undefined"
        return jwtCheck() ? child : <Navigate to="/login" />;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search