I wanted to add extra level of security such that the user only gets to visit the path I have mentioned in Route mentioned with array of paths

Viewed 37

It is giving "A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>" this error I checked the react-router documentation but couldn't find the relevant answer.

This code is to allow the user to only render to the paths specified in the array.

<Route
  path={[
    '/',
    '/invite',
    '/get_username',
    '/code_confirm',
    '/allow_notification',
  ]}
>
  <PlanLayout>
    <Routes>
      <Route path='/' element={<Welcome />} />
      <Route path='/invite' element={<PhoneConfirmation />} />
      <Route path='/code_confirm' element={<CodeConfirm />} />
      <Route path='/allow_notification' element={<AllowNotification />} />
    </Routes>
  </PlanLayout>
</Route>
<Route path={["/home"]}>
  <AppLayout>
    <Routes>
      <Route path='/home' element={<Home />} />
    </Routes>
  </AppLayout>
</Route>
1 Answers

You are rendering something other than a Route in the Routes component. Only Route or React.Fragment are valid children. The Route component also only takes a string path prop value, not an array of strings.

Convert the layout components into layout routes by rendering an Outlet component instead of the children prop.

Example:

import { Outlet } from 'react-router-dom';

const PlanLayout = () => {
  ... any component logic ...

  return (
    <>
      ...
      <Outlet />
      ...
    </>
  );
};

...

import { Outlet } from 'react-router-dom';

const AppLayout = () => {
  ... any component logic ...

  return (
    <>
      ...
      <Outlet />
      ...
    </>
  );
};

Render the layout components as layout routes.

<Routes>
  <Route element={<PlanLayout />}>
    <Route path='/' element={<Welcome />} />
    <Route path='/invite' element={<PhoneConfirmation />} />
    <Route path='/code_confirm' element={<CodeConfirm />} />
    <Route path='/allow_notification' element={<AllowNotification />} />
  </Route>
  <Route element={<AppLayout />}>
    <Route path='/home' element={<Home />} />
  </Route>
</Routes>

For more details see:

Related