Next.js - Make the Link component work like React Router Link
This is a quick post to show how to create a custom Link
component that wraps the built-in Next.js link component to make it work more like the standard link component from React Router. I created it as part of 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 Built-In Link Component
The Next.js Link
component accepts an href
attribute but requires an <a>
tag to be nested inside it to work. Other attributes on the link such as className
must be added to the nested <a>
tag. For more info on the Next.js link component see https://nextjs.org/docs/api-reference/next/link.
Next.js Custom Link Component
This custom link component accepts href
, className
plus any other props, and doesn't require a nested <a>
tag because one is automatically added by the component along with any nested child elements ({children}
).
import NextLink from 'next/link';
export { Link };
function Link({ href, children, ...props }) {
return (
<NextLink href={href}>
<a {...props}>
{children}
</a>
</NextLink>
);
}
Example Usage of Custom Link Component
Here are a couple of examples of how to use the custom link component in a Next.js app.
{/* link with href and class name */}
<Link href="/" className="my-class">Home</Link>
{/* link with nested image */}
<Link href="/another-page" className="another-css-class">
<img src="my-image.png" />
</Link>
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.