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?

Sᴀᴍ Onᴇᴌᴀ
29.5k16 gold badges45 silver badges201 bronze badges
asked Jun 25, 2021 at 21:56
\$\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>
answered Jun 26, 2021 at 16:00
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.