Is this a valid way to Load/Refresh a Page on React Router Dom Link click?

Viewed 39

Issue:

I've been trying to find a way to refresh a page with React Router Dom. I am wondering if my code below is correct and usable.

Expected Results:

I am trying to get the same results as when you click on an Anchor <a href='/'> tag with React.

Current Code:

Below you can find the current code I use. You will find 3 things.

  1. A Reusable Link component
  2. A refresh page function that refreshes at the current location.pathname
  3. A Link component from React Router Dom
function ReusableLink({ label, address }) {        
  function refreshPage() {
    window.location.pathname.reload(false);
  }

  return (
    <li className={path === address ? 'active' : ''}> 
      <Link className='link' to={address} onClick={refreshPage}>
        {label}
      </Link>
    </li>
  )
}
1 Answers

I would only use window.reload in a pinch.

There are two RRD ways I know of, one each depending on the version.

If you are using react-router-dom@6 the Link component has a reloadDocument prop.

Link

interface LinkProps
  extends Omit<
    React.AnchorHTMLAttributes<HTMLAnchorElement>,
    "href"
  > {
  replace?: boolean;
  state?: any;
  to: To;
  reloadDocument?: boolean;
}

You can use <Link reloadDocument> to skip client side routing and let the browser handle the transition normally (as if it were an <a href>).

<Link className='link' to={address} reloadDocument>
  {label}
</Link>

If you are using react-router-dom@5 then the BrowserRouter has a forceRefresh prop.

BrowserRouter

forceRefresh

If true the router will use full page refreshes on page navigation. You may want to use this to imitate the way a traditional server-rendered app would work with full page refreshes between page navigation.

<BrowserRouter forceRefresh>
  ...
</BrowserRouter>
Related