sajad torkamani

Last tested with react-router-dom^6.0.2.

You want to check if the path for a given <Link> component matches the current path. Here’s an approach:

import React from 'react'
import { Link, LinkProps, useMatch, useResolvedPath } from 'react-router-dom'
import classNames from 'classnames'

const AppLink: React.FC<LinkProps> = ({ children, to, ...props }) => {
  const resolvedPath = useResolvedPath(to)
  const isActive = !!useMatch({ path: resolvedPath.pathname, end: true })

  const className = classNames(props.className, 'underline', {
    'font-bold': isActive,
  })

  return (
    <Link to={to} {...props} className={className}>
      {children}
    </Link>
  )
}

export default AppLink

The key part here is using the useResolved and useMatch hooks.

Now, you can use the component anywhere:

<AppLink to="/account-details">Account details</AppLink>

The active class will be applied to the resulting <a> if the current path matches /account-details. I’ve used classnames in the above example but you can use a regular conditional check to apply any class name you wish.

Sources

Leave a comment

Your email address will not be published. Required fields are marked *