Nested Route and Index Route in ReactJS
Implementation : import { BrowserRouter,Routes,Route } from "react-router-dom"
And we have to install that react router
for installation we have to write the script - npm i react-router-dom
1) Simple Route
import { BrowserRouter,Routes,Route } from "react-router-dom"
import Homepage from "./pages/Homepage"
function App(){
return <>
<BrowserRouter>
<Routes>
<Route path="/" element={<Homepage />} />
<Route path="product" element={<Product />} />
</Routes>
</BrowserRouter>
</>
}
// HomePage.jsx
export default function Homepage() {
return (
<h1>Hello</h1>
)}
// Product.jsx
export default function Product() {
return (
<h2>Hello product </h2>
)};
2) Nested Route
import { BrowserRouter,Routes,Route } from "react-router-dom"
function App(){
return <>
<BrowserRouter>
<Routes>
<Route index element={<Homepage />} />
<Route path="product" element={<Product />} />
// Nested Route
<Route path="app" element={<AppLayout />}>
<Route path="cities" element={<CityList/>} />
<Route path='cities/:id' element={<City />} />
<Route path="countries" element={<CountriesList/>} />
<Route path="form" element={<Form />} />
</Route>
</Routes>
</BrowserRouter>
</>
}
Maintain the route if any of the above Route is not touched
// If no Route matches then this will be executed
<Route path="*" element={<PageNotFound />} />
3) Index Route : Look the Difference from the nested route , for creating the index route we have to mention "index" into the <Route />
-> A index route is default route of NESTED ROUTE
<Route path="app" element={<AppLayout />}>
// Index route
<Route index element={<CityList/>} />
<Route path="cities" element={<CityList/>} />
<Route path='cities/:id' element={<City />} />
<Route path="countries" element={<CountriesList/>} />
<Route path="form" element={<Form />} />
</Route>