DEV Community

Discussion on: Creating a link with an active state in Next.js

Collapse
 
lyrod profile image
Lyrod

Uodate 2 : using interpolation to concat both className is not a good idea. If children.props.className is undefined, I think you'll have "undefined className" in the new className

Thread Thread
 
elvessousa profile image
Elves Sousa

That's what happens when you do things in a hurry, hahaah... You were right again. I made this change, what do you think? This was enough to get rid of the undefined.

export function ActiveLink({
  children,
  activeClassName,
  ...rest
}: ActiveLinkProps) {
  const { asPath } = useRouter();
  const childClassName = children.props.className ?? '';
  const newClassName = `${childClassName} ${activeClassName ?? ''}`;
  const className = asPath === rest.href ? newClassName.trim() : '';

  return <Link {...rest}>{cloneElement(children, { className })}</Link>;
}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
lyrod profile image
Lyrod

This is better!