user6398538
user6398538

Reputation:

Conditional Rendering in JSX

How can I do a conditional rendering with JSX?

for instance I have div here where I want to render the text "NO IDEA" if the value of the props in null otherwise render the props if its not equal to null.

For example:

<div>{ return this.props.date === null ? 'NO IDEA' : this.props.date }</div>

I tried this but it did not worked out. Any idea what am doing wrong here?

Thanks in advance!

Upvotes: 0

Views: 3910

Answers (2)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

First of all, you don't need to use return statement inside the expression block. Next thing, don't check just for null, it might be undefined rather:

<div>{ this.props.date ? this.props.date : 'NO IDEA' }</div> 

This simply checks if date is available / true parsed in boolean, then use true value else use false value.

Or, even in simpler syntax using ||:

{ this.props.date || 'NO IDEA' }

This will render the date only if date value is true parsed in boolean otherwise it will render 'NO IDEA'.

Upvotes: 2

sumit
sumit

Reputation: 15464

you can simply use ternary operator based on this.props.date so you do not need return here

<div> {this.props.date === null ? 'NO IDEA' : this.props.date }</div>

Upvotes: 3

Related Questions