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.