0

I'm new to React and I have a problem when I go between pages in the navigation in the home page does not disappear class, tell me what to do.

const Navbar = () => {
    const [isNavShowing, setIsNavShowing] = useState(false);

return (
    <nav>
        <div class="container nav__container">
            <Link to="/" className='logo' onClick = {() => setIsNavShowing(false)}>
                <img src={Logo} alt="Logo" />
            </Link>
            <ul className={`nav__links ${isNavShowing ? 'show__nav' : 'hide__Nav'}`}>
                {
                    links.map(({ name, path }, index) => {
                        return (
                            <li key={index}>
                                <NavLink to={path} className={({isActive}) => isActive ? ' active-nav' : ''} onClick={() => setIsNavShowing(prev => !prev)}>{name}</NavLink>
                            </li>
                        )
                    })
                }
            </ul>
            <button class="nav__toogle-btn" onClick={() => setIsNavShowing(prev => !prev)}>
                {
                    isNavShowing ? <MdOutlineClose/> :<GoThreeBars />
                }
            </button>
        </div>
    </nav>
)
}

Picture: what the problem looks like on the site + google tools

Ahmet Emre Kilinc
  • 5,489
  • 12
  • 30
  • 42
feer deer
  • 11
  • 1

1 Answers1

0

This works as expected since isActive prop returns true if the current location matches the route path. And in your case, route path "/" matches all the subroutes, as a result active-nab class always shows up for Home link.

What you can do is, you can add extra control for the"/" path to check if it is the exact "/" route using useLocation hook like this:

const location = useLocation();

  let exactActive = true;
  if (props.to === "/") {
    if (location.pathname !== "/") {
      exactActive = false;
    }
  }
  return (
    <NavLink
      className={({ isActive }) =>
        isActive && exactActive ? " active-nav" : ""
      }
      {...props}
    />
  );

You can take a look at this sandbox for a live working example of this solution.

Ahmet Emre Kilinc
  • 5,489
  • 12
  • 30
  • 42
  • What about the `exact` prop? – code Sep 19 '22 at 19:35
  • @code Sorry, I could not get what you are asking. What is the `exact` prop? – Ahmet Emre Kilinc Sep 19 '22 at 19:46
  • See [this](https://v5.reactrouter.com/web/api/NavLink/exact-bool) (it's only for v5 though, I think) and https://stackoverflow.com/questions/49162311/react-difference-between-route-exact-path-and-route-path – code Sep 19 '22 at 20:55
  • Oh, I got it, yes it would be a better approach if it works as expected, but I could not make it work with v6. Maybe there is another similar prop in v6 version. Unfortunately, v6's documentation is really insufficient. – Ahmet Emre Kilinc Sep 19 '22 at 21:02