I’m having some difficulty with react routing and having trouble comprehending composed routes. I’ve attempted some code, but unfortunately, it’s not functioning as expected. The "/"
path works perfectly fine, however, when I attempt to access "/child"
, it doesn’t seem to work. I believe there might be an issue with the wrapper route <Route element={<Wrapper/>} />
.
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter, Routes, Route } from 'react-router-dom'
function Home() {
return <h1>its home</h1>
}
function Child() {
return <h1>its child</h1>
}
function Wrapper() {
return(
<div>
<h1>trial</h1>
<Route path="/child" element={<Child />} />
</div>
)
}
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/home" element={<Home />} />
<Route element={<Wrapper />} />
</Routes>
</BrowserRouter>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
2
Answers
The Problem
/child
path in the wrong placeWrapper
componentSimple Solution
<BrowserRouter> <Routes>
Further Reading
Further Solution
Outlet
in your wrapper so you can then use the Wrapper across multiple componentsIt’s unclear what exactly you are meaning when you say "composed routes", but React-Router basically has two types of routes.
Nested Routes:
Route
components directly rendering other (e.g nested)Route
components.Descendent Routes: Routed components rendering another set of
Routes
andRoute
components.Armed with this knowledge now you have a couple basic ways to render the
Child
component on the"/child"
path where it’s accessible/renderable.or
For more details see Layout Routes and Outlets, and Splats.