Reputation: 559
I'm using Tailwinds CSS and classNames package.
I'm rendering out 2 div
s and I want to check if one of them has am active
class, then set a specific background color className bg-[#000]
to it.
'bg-[#000]': 'active'
check but this just inserts the background color on all elements.How can we set a specific style to an active element with Tailwind
and classNames
?
Thank you!
Screenshots:
Here's a screenshot of the tags, the 1st one is currently active.
But the second one which is not active also has the bg-[#000]
class.
Code:
list.map((page, index) => {
return (
<div
key = {index}
onClick = {() => setCurrentListIdx(index)}
className = {
classNames('bullets__item m-1.5 h-2 w-2 cursor-pointer rounded-full bg-[#e0e0e0]',
{
active: currentListIdx === +index,
'bg-[#000]': 'active',
}
)}
></div>
)
})
Upvotes: 1
Views: 2266
Reputation: 102
In the conditional 'bg-[#000]': 'active'
, you're passing the string 'active'
rather than a variable or an expression to evaluate. This is returning true
because JS strings are truthy, and so always adding the class. The classNames
utility doesn't appear to allow checking against currently applied class names in its conditionals object this way.
You could alternatively use the same conditional for both class names: currentListIdx === +index
, so both classes would be added when this condition is met.
Upvotes: 2