React Router v6 Error: [PrivateRoute] is Not a
When using React Router v6 and creating private routes, developers may encounter an error stating, "[PrivateRoute] is not a
Origin of the Problem
This error arises when the "PrivateRoute" component is not being properly rendered as a child of the "
Solution
To resolve this issue, ensure that the PrivateRoute component is defined as a nested child of the Route component within the Routes component, as seen below:
<code class="javascript">// PrivateRoute.js import React from "react"; import { Navigate, Outlet } from "react-router-dom"; const PrivateRoute = () => { const auth = null; // Determine if authorized // Return outlet if authorized, navigate to login otherwise return auth ? <Outlet /> : <Navigate to="/login" />; }; // App.js import React, { Fragment } from "react"; import { BrowserRouter as Router, Route, Routes } from "react-router-dom"; import Navbar from "./components/layout/Navbar"; import Home from "./components/pages/Home"; import Register from "./components/auth/Register"; import Login from "./components/auth/Login"; import PrivateRoute from "./components/routing/PrivateRoute"; const App = () => { return ( <Router> <Fragment> <Navbar /> <Routes> <Route exact path="/" element={<PrivateRoute />}> <Route exact path="/" element={<Home />} /> </Route> <Route exact path="/register" element={<Register />} /> <Route exact path="/login" element={<Login />} /> </Routes> </Fragment> </Router> ); };</code>
In this revised code:
The above is the detailed content of Why Am I Getting the \'[PrivateRoute] is Not a Component\' Error in React Router v6?. For more information, please follow other related articles on the PHP Chinese website!