0

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.

5
  • What do you mean by "page renders even the this.state.keyword is blank"? Commented Feb 13, 2020 at 15:21
  • Do you use JSX? Commented Feb 13, 2020 at 15:23
  • oh, It shows html tags on the webpage, such as <span></span>... Commented Feb 13, 2020 at 15:23
  • That means, this.state.keyword is not null (?) Maybe it's undefined. Commented Feb 13, 2020 at 15:24
  • You could reverse the conditional and ask if keyword is defined { this.state.keyword ? <span>{this.state.keyword}</span> : null } which means, if this.state.keyword is not null or undefined, render the span, otherwise render null. Commented Feb 13, 2020 at 15:28

3 Answers 3

1

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>'+' '} 
Sign up to request clarification or add additional context in comments.

2 Comments

I forgot to mention that this code is inside render{return( {this.state.keyword!=null?' '+'<span>'+this.state.keyword+'</span>'+' ':''} )} section.
You can still use it inside a render method
0

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

4 Comments

I guess that you just wrote something without explaining why it helps?
@Abhay Sehgal your solution works for the textbox but not the dropdown box. If I have a dropwdown Subject, {this.state.subject?' '+'<span>'+this.state.subject+'</span>':' '}, the page does not display this.state.subject value.
What is the value of subject at the time of render?
this.state.subject value is ACC, BIO, etc.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.