How to use Chakra UI Button and Link components with NextJS Link

Emmanuel Gautier / February 04, 2023

2 min read

Chakra UI and Next.js work great together but there is some glue to add to make them work together. My last experiment about it was with the Button and Link Chakra UI components and the Next.js Link components for a website where SEO is important. The Chakra UI components do not generate the HTML <a> tags as I first expected and that broke the website's internal links.

As a first tentative to create a link with a button, I write this React code.

import { Button } from '@chakra-ui/react'
import NextLink from 'next/link'

const MyButton: React.FC = () => (
  <NextLink href="https://app.filendy.com">
    <Button>
      Get Started
    </Button>
  </NextLink>
)

This code renders the following DOM nodes and some JS code to make the link behavior works which works great for user interaction.

<button type="button" class="chakra-button css-1t9x4xi">Get Started</button>

The user views a button, then click on it, and finally, the browser navigates to the new link. Everything is right, isn't it? Not really since this is not a link for crawlers. In my case, it is ahrefs crawler that warns me about some Orphan Pages. Since every link is not rendered as a link, the crawler detects no internal link. The internal linking is broken.

A better way

To replace the button tag with an a tag, you must first passHref to the child components from the Next Link components and use the as props with the tag a to render the Chakra button as a link.

import { Button } from '@chakra-ui/react'
import NextLink from 'next/link'

const MyButton: React.FC = () => (
  <NextLink href="https://app.filendy.com" passHref>
    <Button as="a">
      Get Started
    </Button>
  </NextLink>
)

Here is the HTML generated from the code above:

<a class="chakra-button css-13t2jeh" href="https://app.filendy.com">Get Started</a>

This is the same behavior with the Chakra UI Link and the same solutions. Here is an example with the Chakra Link:

import { Link } from '@chakra-ui/react'
import NextLink from 'next/link'

const MyButton: React.FC = () => (
  <NextLink href="https://app.filendy.com" passHref>
    <Link as="a">
      Get Started
    </Link>
  </NextLink>
)

Consulting

If you're seeking solutions to a problem or need expert advice, I'm here to help! Don't hesitate to book a call with me for a consulting session. Let's discuss your situation and find the best solution together.

Share this post
Follow the RSS feed

Subscribe to the newsletter

Get the latest news about tech new articles and projects.