Home > Web Front-end > JS Tutorial > body text

How to Fix \'[PrivateRoute] is not a component\' Error in React Router v6?

DDD
Release: 2024-11-01 03:16:27
Original
633 people have browsed it

How to Fix

Error: [PrivateRoute] is not a component

This error occurs when using React Router v6 and attempting to create private routes. The given code in PrivateRoute.js attempts to return a Route component, but it is not exported as such.

Solution:

To resolve this issue, modify the PrivateRoute.js file as follows:

import React from 'react';
import { Navigate, Outlet } from 'react-router-dom';

const PrivateRoute = () => {
    const auth = null; // determine if authorized, from context or however you're doing it

    // If authorized, return an outlet that will render child elements
    // If not, return element that will navigate to login page
    return auth ? <Outlet /> : <Navigate to="/login" />;
}

export default PrivateRoute;
Copy after login

In the App.js file, ensure that the private route is defined as follows:

<Route exact path='/' element={<PrivateRoute />}>
  <Route exact path='/' element={<Home />} />
</Route>
Copy after login

This revised code will ensure that the PrivateRoute component is recognized as a Route component and will function properly for private routing.

The above is the detailed content of How to Fix \'[PrivateRoute] is not a component\' Error in React Router v6?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template