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 i
Solution 1:
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>
Solution 2:
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'.
Post a Comment for "Conditional Rendering In Jsx"