close

[Solved] Error: [PrivateRoute] is not a component. All component children of must be a or

Hello Guys, How are you all? Hope You all Are Fine. Today I am trying to use private route and I am facing following error Error: [PrivateRoute] is not a <Route> component. All component children of <Route> must be a <Route> or <React.Fragment> in reactjs. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How this error occur ?

I am trying to use private route and I am facing following error.

Error: [PrivateRoute] is not a <Route> component. All component children of <Route> must be a <Route> or <React.Fragment>

How To Solve Error: [PrivateRoute] is not a <Route> component. All component children of <Route> must be a <Route> or <React.Fragment> Error ?

  1. How To Solve Error: [PrivateRoute] is not a component. All component children of must be a or Error ?

    To Solve Error: [PrivateRoute] is not a <Route> component. All component children of <Route> must be a <Route> or <React.Fragment> Error Follow this example.

  2. Error: [PrivateRoute] is not a component. All component children of must be a or ?

    To Solve Error: [PrivateRoute] is not a <Route> component. All component children of <Route> must be a <Route> or <React.Fragment> Error Follow this example.

Solution 1: For Example

PrivateRoute.js

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" />;
}

App.js

import './App.css';
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>
    
  );
}

This is private route.

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

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read