return (
<BrowserRouter>
<Routes>
<Route path="/parent" element={<h1>I am parent</h1>}>
<Route path="child" element={<h1>I am child</h1>} />
</Route>
<Route
path="*"
element={
<main style={{ padding: '1rem' }}>
<p>There's nothing here!</p>
</main>
}
/>
</Routes>
</BrowserRouter>
When I visit the route http://localhost:3000/parent/child I am expecting the following output.
I am parent I am child
But instead I am getting the output
I am parent
"dependencies": {
"@craco/craco": "^6.4.0",
"@heroicons/react": "^1.0.5",
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"@types/jest": "^26.0.15",
"@types/node": "^12.0.0",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"axios": "^0.24.0",
"js-cookie": "^3.0.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-hook-form": "^7.19.4",
"react-router-dom": "6",
"react-scripts": "4.0.3",
"typescript": "^4.1.2",
"web-vitals": "^1.0.1",
"zustand": "^3.6.5"
},
CodePudding user response:
React v6 needs to know where exactly you want your child element to be displayed, within the parent element. For this, you need to add a <Outlet />
component.
See https://reactrouter.com/docs/en/v6/examples/basic
So your example should be written:
return (
<BrowserRouter>
<Routes>
<Route path="/parent" element={<><h1>I am parent</h1><Outlet /></>}>
<Route path="child" element={<h1>I am child</h1>} />
</Route>
<Route
path="*"
element={
<main style={{ padding: '1rem' }}>
<p>There's nothing here!</p>
</main>
}
/>
</Routes>
</BrowserRouter>