React-router-dom - No routes matching location '/' when Route has param
I'm trying to figure out why passing a param using React-router-dom's Link and Route is not working correctly. My routes are configured this way:
App.tsx
<Routes>
<Route path="/:id" element={<Home />} />
<Route path="/search" element={<Search />} />
</Routes>
Home renders data using a default initial ID, And I am using Link inside the Search component to send an id param to render data in Home using this different id, this way:
Search.tsx
<Link to={`../${idParam}`}>
<li>
Some Link
</li>
</Link>
What I expect: when the URL points to '/', the default Home component should be rendered. When a param is added Home should receive this param and be rendered using the id sent.
However, currently Home will only be rendered when an id is provided as a param (for example: '/1234'). When navigating to '/', React responds with 'No routes matched location "/"'
Appreciate any help clarifying what's wrong with my set-up, thanks!
Now route matches exact path by default. Uptill v5 we could declare a parameter optional by using a question mark symbol(?). But unfortunately its no longer available in v6. Ref - issues Now instead of optional parameter, you can declare children routes under a parent route. Use the code below in App.tsx
<Routes>
<Route path="/">
<Route path=":id" element={<Home />} />
<Route path="" element={<Home />} />
</Route>
<Route path="/search" element={<Search />} />
</Routes>
Also change your code in Search.tsx to
<Link to={`/${idParam}`}>
<li>
Some Link
</li>
</Link>