The problem of repeated matching on the activeClassName home page of react-router

problem to be solved:

clipboard.png
when URL is not the home page ( path="/category" ), the home page (" path="/" ") incorrectly adds activeClassName

first of all, the route pattern is BrowserRouter

import { BrowserRouter as Router, Switch, Route, Redirect } from "react-router-dom";
// ...
class RouteMap extends Component {
  render () {
    return (
      <Router>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/category" component={props => requireAuth(Category, props)} />
          <Route path="/about" component={About} />
          <Route path="/help" component={Help} />
          <Route path="/login" component={Login} />
          <Route component={NotFound} />
          <Redirect to="/" />
        </Switch>
      </Router>
    )
  }
}

export default RouteMap;

then the navigation code is as follows:

import { withRouter, NavLink as Link } from "react-router-dom";
// ...
<li><Link to="/" activeClassName="activeRoute">Home</Link></li>
<li><Link to="/category" activeClassName="activeRoute">category</Link></li>
<li><Link to="/about" activeClassName="activeRoute">about</Link></li>
<li><Link to="/help" activeClassName="activeRoute">Help</Link></li>
Mar.09,2021

resolved:

import { withRouter, NavLink as Link } from 'react-router-dom';
// ...
<li><Link to="/" exact activeClassName="activeRoute">Home</Link></li>

< NavLink >
exact: bool
if true, only if the access address matches exactly, the active style will be applied

strict: bool
if true, only if the access address suffix slash matches exactly (with or without) will the active style be applied

isActive: func
decides whether navigation is activated or does something else when navigation is activated. In any case, it does not determine whether the corresponding page can be rendered.

Menu