Published: May 31 2021

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>

 


Need Some NextJS Help?

Search fiverr for freelance NextJS developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by