Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional className in React?

May be a subtle problem, but i don't like the way it appears when i inspect elements in the browser

Sometimes i need to add a class to an element in react using ternary operator and that may leave some space when the condition returns false

for exampe:

<div className={`container ${some condition ? 'bg-green' : ''}`}

when condition is true, the class is added to the div but when it is false, there is an ugly space shown in the element when inspect

<div class="container  "> 

Is it acceptable?? or a bad practice??, is there a good solution for it?

like image 506
Code Eagle Avatar asked Jan 27 '26 08:01

Code Eagle


1 Answers

That shouldn't be a big issue, but you can remove the space before the ternary operator (and add it in the .bg-green branch)

<div className={`container${some condition ? ' bg-green' : ''}`}

I haven't tried, but you might add a .trim() as well like below, but I don't think you need it.

<div className={`container${some condition ? ' bg-green' : ''}`.trim()}

Demo:

console.log(`"container${true ? ' bg-green' : ''}"`)
console.log(`"container${false ? ' .bg-green' : ''}"`)
like image 107
Balastrong Avatar answered Jan 28 '26 21:01

Balastrong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!