Home  >  Article  >  Web Front-end  >  Why Am I Getting the \'[PrivateRoute] is Not a Component\' Error in React Router v6?

Why Am I Getting the \'[PrivateRoute] is Not a Component\' Error in React Router v6?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-29 11:48:02771browse

Why Am I Getting the

React Router v6 Error: [PrivateRoute] is Not a Component

When using React Router v6 and creating private routes, developers may encounter an error stating, "[PrivateRoute] is not a component. All component children of must be a or ."

Origin of the Problem

This error arises when the "PrivateRoute" component is not being properly rendered as a child of the "" component within the "" component.

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:

  • PrivateRoute is nested within Route, which is in turn nested within Routes.
  • The PrivateRoute component determines authorization and displays the Outlet component (child elements) if authorized.
  • If unauthorized, PrivateRoute navigates to a login page.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn