useNavigate doesn't load page when navigating between siblings component

Viewed 1319

I'm working at a react-js app using react-router-dom v6

I try to simplify my framework to make it clearer.

MainRouter.js

<BrowserRouter>
  <NavBar/>
  <Routes>     
      <Route exact path="/"  element={<HomePage/>}></Route>
      <Route path="item"  element={<ShowItem/>}>
        <Route path=":itemId"  element={<ShowItem/>}>
        </Route>
      </Route>
  </Routes>

The navbar includes a search bar s.t. I'm able to search different items: "item/1", "item/2", ... For sake of semplicity, I replace the search bar with a button which try to redirect always to item 12

NavBsr.js

return (
    [...]
    <button onClick={()=>navigate("/item/12")}>Click</button>
);

If I'm in any page but "item/*", the navigation works as expected. Ex. if I'm at "homepage", the button redirects to "item/12"

However, the strange behaviour happens if my current page is "item/*", ex. "item/1". In this case, if I press the button the url changes to "item/12" but the content doesn't load: the correct content is loaded only if I manually refresh the page

Thanks for any suggestion

1 Answers

The ShowItem component should "listen" for changes to the itemId route param so it can handle fetching data or running any logic that depends on this value.

Use an useEffect hook with a dependency on the itemId route param.

Example:

const { itemId } = useParams();

useEffect(() => {
  if (itemId) {
    // handle logic using new itemId value
  }
}, [itemId]);
Related