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>
Subscribe or Follow Me For Updates
Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.
- Subscribe on YouTube at https://www.youtube.com/JasonWatmore
- Follow me on Twitter at https://twitter.com/jason_watmore
- Follow me on Facebook at https://www.facebook.com/JasonWatmoreBlog
- Follow me on GitHub at https://github.com/cornflourblue
- Feed formats available: RSS, Atom, JSON
Other than coding...
I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.
- Subscribe on YouTube at https://www.youtube.com/TinaAndJason
- Follow us on Instagram at https://www.instagram.com/tinaandjason
- Follow us on Facebook at https://www.facebook.com/TinaAndJasonVlog
- Visit our website at https://tinaandjason.com.au
Need Some NextJS Help?
Search fiverr to find help quickly from experienced NextJS developers.