Reputation: 95
How can I hide with for example "d-none" or similar when the data comes null. I'm working with React.
<span className="product__tag">{prod.tag1}</span>
<span className="product__tag">{prod.tag2}</span>
<span className="product__tag">{prod.tag3}</span>
Upvotes: 0
Views: 1298
Reputation: 105883
You can via CSS use the :empty
selector:
span:empty{display:none;}
Mind the specifity of the selector if span
display
is elsewhere reset.
Upvotes: 2
Reputation: 6736
Method 1:-
<span className="product__tag" style={{display: (prod.tag1 ? 'block':'none')}}>
{prod.tag1}
</span>
Method 2:-
{prod.tag1 && <span className="product__tag">{prod.tag1}</span>}
Method 3:-
{prod.tag1 ? <span className="product__tag">{prod.tag1}</span>: null}
Upvotes: 1
Reputation: 11
Inline Styles
A good way to do this is with inline styles. You can check if your data is null, and display: none based on that.
const checkData = data == null ? "none" : "block"
...
<span style={{display: checkData}} className="product__tag">{prod.tag1}</span>
<span style={{display: checkData}} className="product__tag">{prod.tag2}</span>
<span style={{display: checkData}} className="product__tag">{prod.tag3}</span>
Change the class
This is a similar solution to the last. Instead of changing the style directly, you can change the class and then change the style based on that. This is probably more neat, and better for a larger scale.
const checkData = data == null ? "product__tag__hide" : "product__tag"
...
<span className={checkData}>{prod.tag1}</span>
<span className={checkData}>{prod.tag2}</span>
<span className={checkData}>{prod.tag3}</span>
...
css
.product__tag__hide{
display: none;
}
Upvotes: 1
Reputation: 381
You can try
{prod.tag1 && <span className="product__tag">{prod.tag1}</span>}
Upvotes: 2