'React router dom (6.0.1) child route not working properly
I'm working with react-router-dom v6.0.1 and I'm trying to setup a simple tree structure composed.
The problem is when I link the path /items Router redirectos to Item component. But when i link /items/3 it still redirecting to Items component.
Any tip?
Heres is my code:
import React from 'react'
import {
BrowserRouter,
Routes,
Route,
} from "react-router-dom";
import Home from '../screens/Home';
import Items from '../screens/Items';
import ItemsDetail from '../screens/ItemsDetail';
import NotFound from '../screens/NotFound';
export default function RouteConfig() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="items" element={<Items />}>
<Route path=":itemId" element={<ItemsDetail />} />
</Route>
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
)
}
Solution 1:[1]
you should try separately like this:
<Route path="/items" element={<Items />}>
</Route>
<Route path="/items/:itemId" element={<ItemsDetail />} />
Solution 2:[2]
With react-router-dom v6, we need to define the <Outlet />
in the parent route, where we want the child routes to be rendered.
https://reactrouter.com/docs/en/v6/getting-started/concepts#outlets
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | titleLogin |
Solution 2 | Mile Mijatović |