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?
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' : ''}"`)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With