Active link with React-Router?

JavascriptReactjsEcmascript 6React Router

Javascript Problem Overview


I'm trying out React-Router (v4) and I'm having issues starting off the Nav to have one of the Link's be active. If I click on any of the Link tags, then the active stuff starts working. However, I'd like for Home Link to be active as soon as the app starts since that is the component that loads at the / route. Is there any way to do this?

Here is my current code:

const Router = () => (
  <BrowserRouter>
    <div>
      <Nav>
        <Link activeClassName='is-active' to='/'>Home</Link> {/* I want this to start off as active */}
        <Link activeClassName='is-active' to='/about'>About</Link>
      </Nav>
      
      <Match pattern='/' exactly component={Home} />
      <Match pattern='/about' exactly component={About} />
      <Miss component={NoMatch} />
    </div>
  </BrowserRouter>
)

Javascript Solutions


Solution 1 - Javascript

This is an old, outdated answer for React Router v4


<Link> no longer has the activeClassName or activeStyle properties. In react-router v4 you have to use <NavLink> if you want to do conditional styling:

const Router = () => (
  <BrowserRouter>
    <div>
      <Nav>
        <NavLink exact={true} activeClassName='is-active' to='/'>Home</NavLink>
        <NavLink activeClassName='is-active' to='/about'>About</NavLink>
      </Nav>

      <Match pattern='/' exactly component={Home} />
      <Match pattern='/about' exactly component={About} />
      <Miss component={NoMatch} />
    </div>
  </BrowserRouter>
)

I added an exact property to the home <NavLink>, I'm fairly sure that without it, the home link would always be active since / would match /about and any other pages you have.

Solution 2 - Javascript

React Router v6:

Source: Active NavLink Classes with React Router

Now you can use the className property which now accepts a function and passes an isActive boolean property, like this:

<NavLink
  to="users"
  className={({ isActive }) => (isActive ? 'active' : 'inactive')}
>
  Users
</NavLink>

You can also adding multiple classes too, since v6 is out:

<NavLink
  to="users"
  className={({ isActive }) =>
    isActive ? 'bg-green-500 font-bold' : 'bg-red-500 font-thin'
  }
>
  Users
</NavLink>

Live demo: Active NavLink Classes with React Router

Solution 3 - Javascript

In my case <NavLink /> automatically set active class to items so I use the following method

myComponet.js

<ListItem component={NavLink} to="/somewhere" className="myactive" > something </ListItem>

myStyle.css

a.active.myactive {
 // some styles
}

Solution 4 - Javascript

import { NavLink, useMatch, useResolvedPath } from 'react-router-dom';

const CustomNavLink = ({ to, title }) => {
   let resolved = useResolvedPath(to);
   let match = useMatch({ path: resolved.pathname, end: true });

   return (
      <NavLink to={to} className={`d-flex align-items-center py-2 px-4 ${match ? 'cta-btn' : 'c-n-b-link'}`} >
        <span className='ms-1 f-w-600'>{title}</span>
      </NavLink>
)
}

For React router V6The above custom component will return a navlink that an active class can be activated whenever the path matches the given to path.

Solution 5 - Javascript

As an addition to @Nick's answer (React Router v6), for those who needs the active navigation state in the upper context..

Conditional rendering might be a use case for the need. For ex: if it is active render the filled icon otherwise render the regular one.

This could be achieved by finding the route that we are currently in and then we can do the conditional rendering operation however it would be a little cumbersome.

Instead, we can write a function that modifies the state in Navlink's style prop as following..

  const [active, setActive] = useState('home')

  const activate = (isActive, path, activeStyle, nonActiveStyle) => {
    if (isActive) {
      setActive(path)
      return activeStyle
    }
    return nonActiveStyle
  }

  return (
    <nav>
      <NavLink
        to="/"
        style={(activeNav) => activate(activeNav.isActive, 'home')}
      >
        {active === 'home' ? <HomeFill /> : <Home />}
      </NavLink>
      <NavLink
        to="/profile"
        style={(activeNav) => activate(activeNav.isActive, 'profile')}
      >
        {active === 'profile' ? <ProfileFilled /> : <Profile />}
      </NavLink>
    </nav>
  )

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSaadView Question on Stackoverflow
Solution 1 - JavascriptworcView Answer on Stackoverflow
Solution 2 - JavascriptChilaxathorView Answer on Stackoverflow
Solution 3 - JavascriptNimaView Answer on Stackoverflow
Solution 4 - JavascriptLive Software DeveloperView Answer on Stackoverflow
Solution 5 - JavascripteneskiView Answer on Stackoverflow