\$\begingroup\$
\$\endgroup\$
1
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?
-
\$\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\$Sᴀᴍ Onᴇᴌᴀ– Sᴀᴍ Onᴇᴌᴀ ♦2021年06月28日 20:25:49 +00:00Commented Jun 28, 2021 at 20:25
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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>
answered Jun 26, 2021 at 16:00
lang-css