In React Router v6, I'm trying to create a dynamic SubHeader component that changes based on a particular route or route param. For context, here's a contrived setup:
export const App = () => {
return (
<BrowserRouter>
<Header>
<TopHeader />
<DynamicSubHeader /> // <-- here
</Header>
<Routes>
<Route path="products" element={<Products />} />
<Route path='product/:id/*' element={<ProductDetail />} >
<Route path="price" element={<ProductDetailPrice />} />
</Route>
</Routes>
</BrowserRouter>
)
}
I'd like to update <DynamicSubHeader /> with different content when navigating between /products, /products/:id and even /products/:id/price
Inside <DynamicSubHeader />, I've tried to use the useParam hook provided by react-router-dom, but it just returns null or the data doesn't persist. It seems you can only use useParam when it's nested inside the <Routes> component.
I've also tried using the useLocation hook to listen for route change and manually setting state there, but it doesn't persist either.
For the time being, I've treated <Header /> as a Layout-component that I've placed in each route. Am I using React Router wrong? Otherwise, any suggestions on how to approach this?