How can I add multiple path for home page with react router dom 6?

Viewed 1547

I'm using react router dom 6

I want to load Login component for 3 paths:

/ & /login & /home

I tried by this path:

<Route path='/(home|login)/' element={<Login />} />

but it doesn't work...

5 Answers

Easiest way:

<Route path='/' element={<Login />} />
<Route path='/login' element={<Login />} />
<Route path='/home' element={<Login />} />

Not a react pro, but I believe it can be achieved through components.

  1. Create one home component/page.
  2. in your route '/', 'login' or 'home' call that page/component.
<Route path="/" element={<YourComponent />} />

<Route path="/login" element={<YourComponent />} />

<Route path="/home" element={<YourComponent />} />

You can try this

<Route path={['/', '/login', '/home']} element={<Login />} />

In react-router-dom v6 the Route component's path prop takes only a single string path value, not an array like previous versions did.

Route

declare function Route(
  props: RouteProps
): React.ReactElement | null;

interface RouteProps {
  caseSensitive?: boolean;
  children?: React.ReactNode;
  element?: React.ReactElement | null;
  index?: boolean;
  path?: string; // <-- string type only
}

You will need to render individual routes for each path.

<Route path='/' element={<Login />} />
<Route path='/home' element={<Login />} />
<Route path='/login' element={<Login />} />

Or abstract this utility into a function (not a component!). It needs to be a function call as only Route or React.Fragment components are valid children of the Routes component.

const renderPaths = (paths, Element) =>
  paths.map((path) => <Route key={path} path={path} element={Element} />);

...

<Routes>
  {renderPaths(["/", "/home", "/login"], <Login />)}
</Routes>

Edit how-can-i-add-multiple-path-for-home-page-with-react-router-dom-6

Related