Using Next.js Link with Chakra UI Link

How to use Next.js link properly with Chakra UI.

Next.js with Chakra UI has become my go-to front end stack for creating websites and web apps. Chakra UI’s simple API coupled along with styled system props has made my workflow much faster.

Next.js Link and Chakra UI Link

Like most front-end frameworks, Next.js has a special Link component that is used for navigating between routes. You wan't to make sure you use Chakra UI's Link so that you can maintain consistent styling in your app.

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

<NextLink href={'/'} passHref>
  <Link>Link</Link>
</NextLink>

Wrapping the Chakra UI Link with NextLink and adding the passHref prop will allow the href to be passed as a prop to the Link and will have the NextLink route handler.

Detecting Active Link with Next.js

If you have a link that you want to style if it's the current active page then you can use the useRouter hook that comes with Next router.

import { useRouter } from 'next/router'

const router = useRouter()
const isActive = router.pathname === '/'

<NextLink href={'/'} passHref>
    <Link color={isActive ? 'red' : 'blue'}>Link</Link>
</NextLink>

Have some feedback on this post? .