1

I have multiple routes in my project and for now I want to redirect '/' url to '/path1' everytime the page loads. I tried making '/path1' as the index route but it is keeping me '/' url only i.e the Home component. How do I make it go to path1?

    <Routes>
 <Route path="/" element={<Home/>} >
            <Route index path="path1" element={<OneComponent/>} />
            <Route path="path2" element={</TwoComponent>} />
            <Route path="path3" element={<ThreeComponent/>} />
            </Route>
          </Routes> 
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Aayushi
  • 1,736
  • 1
  • 26
  • 48

1 Answers1

-1

It look like you are trying to use a Layout. Here is an example on how you can implement it :

App.jsx :

import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './home.jsx';
import Layout from './layout.jsx';
import Page1 from './page1.jsx';
import Page2 from './page2.jsx';

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<Home />} />
          <Route path="page1" element={<Page1 />} />
          <Route path="page2" element={<Page2 />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

layout.jsx:

import React from 'react';
import { Outlet, Link } from 'react-router-dom';

const Layout = () => (
  <div>
    <ul>
      <li>
        <Link to="/">Home</Link>
      </li>
      <li>
        <Link to="page1">Page 1</Link>
      </li>
      <li>
        <Link to="page2">Page 2</Link>
      </li>
    </ul>
    <br />
    <Outlet />
  </div>
);

export default Layout;

Note the use of <Outlet /> in the layout that allow you to display the index route. The index route will be rendered when the path defined in the parent is hit. Here it's "/" from <Route path="/" element={<Layout />}>.

Also note that this does not make changes in your url. By that I mean there is no defined url for Layout since it is not really a common route. If you want your parent route (here layout) to have its own url, then you could use nested routes and use <Navigate to="whatever" />.

Here is a repro on Stackblitz if you want to play with routes.

Quentin Grisel
  • 4,794
  • 1
  • 10
  • 15