MENU
Link
The <Link> component is a React wrapper for the HTML <a> element, offering prefetching and client-side navigation between routes. It is the main method for navigating between pages in Next.js.
The fonts have been deliberately enlarged to allow scrolling.
In Next.js, you can change the URL in the browser's address bar without reloading the page by using the useRouter() hook or the Router object provided by Next.js. This allows you to perform client-side navigation and update the URL dynamically.
If the prefetched data expires before the user hovers over a <Link />, Next.js will attempt to prefetch it again. Prefetching is only active in production environments. The prefetch prop accepts the following values:
- null (default): For static routes, the entire route (including all data) is prefetched. For dynamic routes, only the nearest segment with a loading.js boundary is prefetched.
- true: Prefetches the complete route, including data, for both static and dynamic routes.
- false: Disables prefetching entirely, whether on hover or when the route enters the viewport.
If the child of a <Link> is a custom component that wraps an <a> tag, you must include the passHref attribute in <Link>. This is crucial when using libraries like styled-components; without it, the <a> tag won't have an href attribute, which can harm accessibility and SEO.
If you're using ESLint, the next/link-passhref rule ensures proper usage of passHref. Additionally, if you're using Emotion's JSX pragma feature (@jsx jsx), passHref is required even when wrapping an <a> tag directly.
The custom component should also support the onClick property to ensure navigation triggers correctly.
import Link from 'next/link'
import styled from 'styled-components'
// This creates a custom component that wraps an <a> tag
const RedLink = styled.a`
color: red;
`
function NavLink({ href, name }) {
return (
<Link href={href} passHref legacyBehavior>
<RedLink>{name}</RedLink>
</Link>
)
}
export default NavLink;
If the child of a <Link> is a functional component, you must use passHref and legacyBehavior while also wrapping the component with React.forwardRef.
import Link from 'next/link'
import React from 'react'
// Define the props type for MyButton
interface MyButtonProps {
onClick?: React.MouseEventHandler<HTMLAnchorElement>
href?: string
}
// Use React.ForwardRefRenderFunction to properly type the forwarded ref
const MyButton: React.ForwardRefRenderFunction<
HTMLAnchorElement,
MyButtonProps
> = ({ onClick, href }, ref) => {
return (
<a href={href} onClick={onClick} ref={ref}>
Click Me
</a>
)
}
// Use React.forwardRef to wrap the component
const ForwardedMyButton = React.forwardRef(MyButton)
export default function Page() {
return (
<Link href="/about" passHref legacyBehavior>
<ForwardedMyButton />
</Link>
)
}