0

I am building a simple application using React Router. Here is the code which I currently have:

function App() {
    return (
        <Routes>
            <Route path='/Login' element={<Login />}></Route>
            <MyRoute />
        </Routes>
    )
}

const MyRoute = (props) => {
    return <Route path='/Dashboard' element={<Dashboard />}/>
}

export default App

Whenever I do this I am getting the following error:

utils.ts:757 Uncaught Error: [ProtectedRoute] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
at invariant (utils.ts:757:1)
at components.tsx:563:1
at react.development.js:1195:1
at react.development.js:1158:1
at mapIntoArray (react.development.js:1049:1)
at mapIntoArray (react.development.js:1099:1)
at mapChildren (react.development.js:1157:1)
at Object.forEachChildren [as forEach] (react.development.js:1194:1)
at createRoutesFromChildren (components.tsx:547:1)
at Routes (components.tsx:379:1)

But if I return the actual Route component then there is no error. My doubt is that why isn't this working even when I am returning a Route element from MyRoute?

Please comment if more information is needed.

  • https://stackoverflow.com/questions/69864165/error-privateroute-is-not-a-route-component-all-component-children-of-rou – Jack Ecuyer Oct 31 '22 at 10:40

1 Answers1

0

This is the intended behavior of react-router v6 (see official FAQ).

Your logic should be handled through the element. For example, to implement the concept ofProtectedRoute, you can do:

const ProtectedRoute = ({ isConnected }) => {
  if (!isConnected) {
    return <Navigate to="/landing" replace />;
  }

  return <Outlet />;
};

function App() {
    return (
        <Routes>
            <Route path='/Login' element={<Login />}></Route>
            <Route element={<ProtectedRoute isConnected={...} />}>
                <Route path='/Dashboard' element={<Dashboard />}/>
                <Route path='/OtherPrivateStuff' element={<OtherPrivateStuff />}/>
            </Route>
        </Routes>
    )
}

export default App

The <Outlet /> component here will get the matching route among the children of the container route.

Source: React Router 6: Private Routes (alias Protected Routes)

rocambille
  • 15,398
  • 12
  • 50
  • 68