Published:

Next.js - NavLink Component Example with Active CSS Class

This is a quick post to show how to create a custom NavLink component in Next.js that extends the built-in Link component to add the CSS className "active" when the href attribute matches the current URL. It's based on the nav link component from a Next.js CRUD example I posted recently, for full details including a working demo see Next.js 10 - CRUD Example with React Hook Form.


Next.js Custom NavLink Component

This is the NavLink component, by default the "active" class is added when the href matches the start of the URL pathname, use the exact property to change it to an exact match with the whole URL pathname.

import { useRouter } from 'next/router';
import Link from 'next/link';
import PropTypes from 'prop-types';

export { NavLink };

NavLink.propTypes = {
    href: PropTypes.string.isRequired,
    exact: PropTypes.bool
};

NavLink.defaultProps = {
    exact: false
};

function NavLink({ href, exact, children, ...props }) {
    const { pathname } = useRouter();
    const isActive = exact ? pathname === href : pathname.startsWith(href);

    if (isActive) {
        props.className += ' active';
    }

    return (
        <Link href={href}>
            <a {...props}>
                {children}
            </a>
        </Link>
    );
}


Example Usage of NavLink Component

Here are a couple of examples of how to use the custom nav link component in a Next.js app.

{/* nav link with exact match so it only matches on the home page url '/' */}
<NavLink href="/" exact className="nav-item nav-link">Home</NavLink>

{/* nav link matching all urls beginning with '/users' */}
<NavLink href="/users" className="nav-item nav-link">Users</NavLink>

 


Need Some NextJS Help?

Search fiverr to find help quickly from experienced NextJS developers.


Exclusive Semrush Special Offer

FREE 14-day PRO trial to Semrush is available to visitors of this blog. Check your website health quickly and easily with the Semrush all-in-one site auditing tool, eliminate technical SEO issues and optimize your website's speed and performance.


Supported by