user788448
user788448

Reputation: 797

Hide Html Tag When Null

I want to wrap html tags around react state value when the value is not null, ie.

{this.state.keyword!=null?' '+'<span>'+this.state.keyword+'</span>'+' ':''} 

but now, the page renders even the this.state.keyword is blank. How to do it? Thanks.

Upvotes: 0

Views: 490

Answers (3)

user788448
user788448

Reputation: 797

Duh, I moved tag out of the curly brace like this {this.state.keyword!=null?' '+this.state.keyword+' ':''} and solve the problem. Thanks everyone.

Upvotes: 0

Abhay Sehgal
Abhay Sehgal

Reputation: 1723

You can achieve this by :

{ this.state.keyword? ' '+'<span>'+this.state.keyword+'</span>'+' ':''}

Explanation : in your code you're checking for null only whereas you can check for all falsy conditions (eg null, undefined, empty string, 0 and false) by using above condition

Upvotes: 0

Daniel B.
Daniel B.

Reputation: 2611

Use !this.state.keyword instead of this.state.keyword!=null

!this.state.keyword will check for all falsy values, like null, 0, empty string (not undefined though)

{!this.state.keyword ? '' : '<span>'+this.state.keyword+'</span>'+' '} 

Upvotes: 1

Related Questions