icode
icode

Reputation: 717

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>
  }

Upvotes: 13

Views: 38744

Answers (4)

Mr Coder
Mr Coder

Reputation: 523

here new exaple for new developer

const [ role, setRole ] = useState('');

const onClick = () => setRole('admin');

<input type='button' onClick={onClick} value='i am admin' />

   {role == 'admin' &&
    <div className='admin'>{'this section view using react... '}
      </div>    
  }

Upvotes: 0

speckledcarp
speckledcarp

Reputation: 6375

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> : ''}

Upvotes: 14

icode
icode

Reputation: 717

Simple use case for now.

{this.props.test === true &&
    <div>if true show</div>
  }

Upvotes: 28

Aakash
Aakash

Reputation: 1515

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.

Upvotes: 7

Related Questions