Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Next.js <Link> prefetch for a <button>? (And avoiding a double selection while navigating with Tab key)

Accessibility best practices suggest using <button> for button elements.

Prefetching for Next.js can be done via <Link>.

However, when you combine the two and use the Tab key to navigate, it will essentially select that button twice. E.g.

<Link href="#">
  <a>
    This selects once
  </a>
</Link>

<Link href="#">
  <a>
     <button>
       This selects twice
     </button>
  </a>
</Link>

You could do something like this:

<button
  onClick={() => { window.location.href "#" }
>
  This only selects once
</button>

But that doesn't prefetch.

like image 623
Chris Avatar asked Jan 19 '26 17:01

Chris


1 Answers

You can use router.prefetch to fetch the route before going to the page. Check this for more details

export default function Login() {
  const router = useRouter()
  const onClick = useCallback((e) => {
      router.push('/dashboard')
  }, []);

  useEffect(() => {
    router.prefetch("/dashboard"); // Prefetch the dashboard page
  }, [])

  return (
      <button onClick={onClick}>Login</button>
  )
}
like image 51
Rahul Sharma Avatar answered Jan 22 '26 06:01

Rahul Sharma