Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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.

>Solution :

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>
  )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading