phantom phantom - 9 days ago 6
React JSX Question

React: conditional statement in render function

I have an array of objects with different artists. I want to show different content based on whether or not an image is in the individual object.

I have tried to put an

if/else
statement in my render method, but of course this is not working. Please see my code below.

render: function() {
var cardList = this.props.artists.map(function(artist, index){
return(
<li key={index} className='card'>
<span>
{if artist.image}
<img src="{artist.image}">
{else}
<p>{artist.message}</p>
<p>LIKES <i className="fa fa-heart" aria-hidden="true"></i> {artist.likeCount }</p>
</span>
</li>
)
})
return (
<div className='tickerwrapper'>
<ul className='list'>{cardList}</ul>
</div>
)
}

Answer

You can inline something along the lines of:

{ myVal === true ? <div>True</div> : <div>False</div> }

If, for example you only want something rendered if myVal is true you can do return null if it's false:

 { myVal === true ? <div>True</div> : null }

If the logic is quite large just extract it into a function and call that from within your render:

renderSalutation() {
  return (userLoggedOn ? <h3>Hello!</h3> : null);
}

render() {
  return (
    <div>
      { this.renderSalutation() }

      ------other renderings here

    </div>  
  );
}