Home >Web Front-end >JS Tutorial >How to Fix \'[PrivateRoute] is not a component\' Error in React Router v6?

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

DDD
DDDOriginal
2024-11-01 03:16:27682browse

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;

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>

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!

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