Re-render the React Router component by clicking the link yourself.
P粉295728625
P粉295728625 2023-07-27 22:31:16
0
1
496
<p>I use <code>react-router-dom</code> v6</p> <h1>code</h1> <pre class="brush:php;toolbar:false;"><NavLink to="/pathOne" className="ripple">label1</NavLink> <NavLink to="/pathTwo" className="ripple">label2</NavLink></pre> <h1>Question</h1> <p>When you click one link or another, the Route component renders as expected. However, if "/pathOne" is active and I click on it again, nothing happens. </p><p>Is there a way to force a route element to be re-rendered by clicking on an active link? </p><p>I could refresh the entire page if the reloadDocument attribute was set, but that's not a viable option. </p><p><code></code></p>
P粉295728625
P粉295728625

reply all(1)
P粉432906880

If all you really want is for the route component to rerender each time the link to its route is clicked then just have those components call the useLocation hook. Each time the link is clicked a new location object reference is created. The new location object reference is enough to trigger the component using it to be rerendered.

Example:

const PathOne = () => {
  useLocation();

  useEffect(() => {
    console.log("PathOne rerender");
  });

  return <h1>PathOne</h1>;
};

const PathTwo = () => {
  useEffect(() => {
    console.log("PathTwo rerender");
  });

  return <h1>PathTwo</h1>;
};
function App() {
  return (
    <div className="App">
      <NavLink to="/pathOne" className="ripple">
        label1
      </NavLink>
      <NavLink to="/pathTwo" className="ripple">
        label2
      </NavLink>
      <Routes>
        <Route path="/pathOne" element={<PathOne />} />
        <Route path="/pathTwo" element={<PathTwo />} />
      </Routes>
    </div>
  );
}

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template