react router highlight in navbar current route in typescript

Assuming you have a navbar component and that you are using React Router DOM and typescript in your project, you can highlight the active route in the navbar by using the NavLink component provided by React Router.

Here's an example of how to use it:

index.ts
import { NavLink } from 'react-router-dom';

interface NavbarProps {
  // Your props
}

const Navbar: React.FC<NavbarProps> = (props) => {
  return (
    <nav>
      <ul>
        <li>
          <NavLink exact to="/" activeClassName="active">
            Home
          </NavLink>
        </li>
        <li>
          <NavLink to="/about" activeClassName="active">
            About
          </NavLink>
        </li>
        <li>
          <NavLink to="/contact" activeClassName="active">
            Contact
          </NavLink>
        </li>
      </ul>
    </nav>
  );
};

export default Navbar;
599 chars
32 lines

Here, we are using the NavLink component and passing in the to prop, which specifies the path to the route we want to link to. We also pass in the activeClassName prop, which specifies the CSS class to apply to the link when it is active.

In this example, we have three links: Home, About, and Contact. When one of these links is active, the activeClassName will be applied to the link, allowing you to style it differently (such as applying a different background color or font weight) to indicate that it is the current route.

Hope this helps!

gistlibby LogSnag