2
\$\begingroup\$

I'm starting to learn React/NextJS and find the way to write conditional CSS very ugly compared to VueJS. I'm curious if someone could look over this code snippet and guide me in the right direction towards a cleaner way of designing my React code.

<Link key={link.text} href={link.to}>
    <a className={`border-transparent border-b-2 hover:border-blue-ninja ${
        activeClass === link.to ? 'active' : ''
    }`}>
        {link.text}
    </a>
</Link>

Is this best practice?

\$\endgroup\$
1
  • \$\begingroup\$ I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). See the section What should I not do? on What should I do when someone answers my question? for more information \$\endgroup\$ Commented Jun 28, 2021 at 20:25

1 Answer 1

2
\$\begingroup\$

You could use a conditional className utility. There are several solutions in the ecosystem, but I would recommend clsx.

Your example would then be:

<Link key={link.text} href={link.to}>
    <a className={clsx('border-transparent border-b-2 hover:border-blue-ninja', { active: activeClass === link.to } )}>
        {link.text}
    </a>
</Link>
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.