Poipoi
Poipoi

Reputation: 225

How to reload the page using React-Router's NavLink?

I use NavLink to highlight buttons with active link, but want to load page like anchor tag. Is it possible to do that?

Upvotes: 3

Views: 8616

Answers (2)

Zachary Haber
Zachary Haber

Reputation: 11047

In addition to Ajeet's answer, here's another way to do it if you need just the links in question to refresh the whole page, but want to work like a single page application otherwise:

This is essentially just making a quick version of the NavLink that uses normal a tags instead of using react-router to change routes. This definitely doesn't include all of the functionality that the NavLink supports, but that could be added in as needed.

import React from "react";
import { useRouteMatch } from "react-router-dom";

export const FakeNavLink = ({
  children,
  to,
  className = "",
  style = {},
  activeClassName = "active",
  basename = "",
  activeStyle = {},
  exact,
  strict
}) => {
  const active = useRouteMatch({ path: to, exact, strict });
  let styleObj = style;
  if (active) {
    styleObj = { ...styleObj, ...activeStyle };
  }
  return (
    <a
      href={basename + to}
      className={className + (active ? ` ${activeClassName}` : "")}
      style={styleObj}
    >
      {children}
    </a>
  );
};

CodeSandbox

Upvotes: 1

Ajeet Shah
Ajeet Shah

Reputation: 19863

You can set forceRefresh property of BrowserRouter to true:

import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';

export default function BasicExample() {
  return (
    <Router forceRefresh>
      <div>
        <Link to="/">Home</Link>
      </div>
      <Switch>
        <Route exact path="/">
          <Home />
        </Route>
      </Switch>
    </Router>
  )
}

It will reload the whole page when you click on a link made with <Link> or <NavLink> for the whole application. But if you want to reload just for a single <Link>, I think you will have to do it in some other way like window.location.reload().

Here is CodeSandbox.

Upvotes: 4

Related Questions