3

As Danilo pointed out in the comments this is a duplicate of Forcing a React-Router <Link> to load a page, even if we're already on that page


I have a route that has a simple navbar and content below it.

The <Link> from react-router-dom does nothing when clicked on the same page's url.

<Route path="/samePage" component={Component} />
import React from 'react';
import { Link } from 'react-router-dom';

function SomeNavBar(){
   return (
      <Link to="/samePage">Refresh</Link>
   );
}

function Component(){
    // some state
    let [data, setData] = useState([]);

    useEffect(()=>{
      // fetch data from API here
    });

    return (
    <>
       <SomeNavBar />
       {/* Displaying the state*/}
    </>);
}

I'd like to refresh the state on the click of the Link in the NavBar. So one option is to use <a href> instead of <Link to="" /> because it will reload the page and does what's desired.

But reloading is bad as we're using React so how can I re-render the route on click?

Phani Rithvij
  • 4,030
  • 3
  • 25
  • 60
  • Are you basically trying to create a button that refetches data from your API? – Drew Reese Jul 09 '20 at 09:18
  • That can be done but I'd like to change the behavior of the `Link` so that when I click on it from a different route I go to the route which the Link points to, whereas if I'm on the same page I need it to act as a button which re-renders the current route's component. I thought there might be an inbuilt way to do this without handling this myself. – Phani Rithvij Jul 09 '20 at 09:21
  • Refresh the state on the click of the Link -> `onClick={() => setData([])}` ? – dejoma Jul 09 '20 at 09:36
  • 1
    Maybe you can find the answer here https://stackoverflow.com/questions/38839510/forcing-a-react-router-link-to-load-a-page-even-if-were-already-on-that-page – Danilo Gacevic Jul 09 '20 at 09:38
  • @DaniloGacevic thanks for finding that question. I wasn't able to get it on google so I had to ask this. This can be closed as a Duplicate. – Phani Rithvij Jul 10 '20 at 09:40

0 Answers0