Repeatable document links and useRouter for active classes

My site uses a menu doctype to build a flexible menu. I'm trying to set up the links to have an active class when on their using useRouter() which works well for singleton docs linkss but for some reason the below code won't recognise/add the class to the doc links from repeatable types:

const DocLink = ({ children, link, linkClass }) => {
  if (link) {
    const linkUrl = Link.url(link, linkResolver)

    const router = useRouter()
    const style = {
      color: router.pathname === linkUrl ? 'red' : 'black',
    }

    const handleClick = (e) => {
      e.preventDefault()
      router.push(linkUrl)
    }

    // If the link is an internal link, then return a NextLink
    if (link.link_type && link.link_type === 'Document') {
      return (
        <NextLink
          as={linkUrl}
          href={Link.url(link, hrefResolver)}
        >
          <a onClick={handleClick} style={style} className={`lg:border-b-2 lg:border-transparent lg:transition-all lg:ease-in-out lg:duration-200 hover:border-black ${linkClass}`}>{children}</a>
        </NextLink>
      )
    }

    // Otherwise return a normal anchor element
    return (
      <a className={linkClass} href={linkUrl}>{children}</a>
    )
  }
  return null
}

export default DocLink

Any tips would be greatly appreciated.

Hello,

After looking down at your code, There are 2 resolvers you are using hrefResolver and linkResolver. Here, I believe you are already getting the required link by
const linkUrl = Link.url(link, linkResolver)
Can you try to use:
href={linkUrl}> instead of href={Link.url(link, hrefResolver)} in NextLink in your code?

linkResolver is the one Prismic has recommended using and is well-defined for your code.

Let me know if I am correct in understanding.

Thanks,

Priyanka

Hi Priyanka,

Thanks for your response. That's not quite what I was after. I've used the solution here to get an active class.

Cheers,
Mike

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.