Reputation: 1222
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?
Upvotes: 14
Views: 11350
Reputation: 10112
Is it acceptable?? or a bad practice??, is there a good solution for it?
It's totally acceptable, and not a bad practice: it doesn't make any practical difference to the HTML if there's some extra space in a class attribute.
One neat solution, which also simplifies, eg. using multiple conditional classes, is to use the classnames
package. This is a small JavaScript utility function for this exact purpose (ie. conditionally setting classes). Using classnames
your example would look something like:
import classNames from 'classnames';
...
<div className={classNames('container', { 'bg-green': someCondition })}>
...this way the container
class will always be present, and the bg-green
class will be present only when someCondition
is true
. This makes it easy to add more conditional classes if you need to (you can add more keys to that object), and you don't need to worry about whitespace.
Upvotes: 1
Reputation: 4464
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' : ''}"`)
Upvotes: 15
Reputation: 14179
That shouldn't really bother you too much, it's not a big deal...
Anyway, add the spacing as part of the condition to solve it:
<div className={`container${someCondition ? ' bg-green' : ''}`}
or
const classes = ['container'].concat(condition ? 'foo' : [];
return <div className={classes.join(' ')} />
Upvotes: 2