Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React show these div if true

I'm still new to React and having a hard time trying to figure out how to show div element content if props return true. I know I can only return one render in a function but how can I achieve this. Can I write some type Jsx inline if statement?

<div>if true show</div> 
<div>if true show</div> 
<div>false don't show</div> 
<div>if true show</div> 

Update: I actually used

{this.props.test === true &&
    <div>if true show</div>
  }
like image 997
icode Avatar asked May 16 '17 01:05

icode


3 Answers

Simple use case for now.

{this.props.test === true &&
    <div>if true show</div>
  }
like image 103
icode Avatar answered Oct 10 '22 17:10

icode


If you're looking for something concise, although not necessarily more readable you can use a ternary operator.

{this.props.test ? <div>if true show</div> : ''}
like image 26
speckledcarp Avatar answered Oct 10 '22 19:10

speckledcarp


Here are 2 ways you can achieve what you want:

1) It is a bit verbose, but it permits to easily split your logic in smaller, focused blocks.

maybeRenderPerson: function() {
    var personName = ...;
    if ( personName ) {
        return <div className="person">{personName}</div>;
    }
}

render: function() {
    return (
       <div className="component">
          {this.maybeRenderPerson()}
       </div>
    );
}

2) This syntax can be quite dangerous if the tested variable can be falsy values like 0,"" or false. Particularly with numbers you should rather modify the test slightly if you want to make sure it renders for 0.

render: function() {
    var person= ...; 
    var counter= ...; 
    return (
        <div className="component">
          {person && (
            <Person person={person}/>
         )}
         {(typeof counter !== 'undefined') && (
             <Counter value={counter}/>
         )}
       </div>
    );
}

Ass suggested by Matt, you can find more info on conditional rendering here.

like image 26
Aakash Avatar answered Oct 10 '22 18:10

Aakash