Reputation: 289
I want to render two buttons based on some state condition using ternary operator just to avoid code repetition.
What I am trying to do?
I have two buttons Cancel and Start based on state value load_cancel
. If Cancel button clicked load_cancel
set to true
and when load_cancel
set to false
Start button is displayed. So I have something like this in the render
method
{props.item_id && this.props.load_cancel &&
<button onClick=
{this.props.handle_load_start}>start</button>}
{props.item_id && !this.props.load_cancel &&
<button onClick={this.props.handle_load_cancel}>Cancel</button>}
How do I do the same using ternary operator?
Thanks.
Upvotes: 3
Views: 663
Reputation: 198
You could do:
const { item_id, load_cancel } = this.props;
const button = item_id ? (
<button onClick={this.handleClick}>{load_cancel ? 'Start' : 'Cancel'}</button>
) : null;
And in handleClick you cand either call this.props.handle_load_start
or this.props.handle_load_cancel
depending on your props.
This way you only write jsx for button once.
Upvotes: 0
Reputation: 45106
Something like this
prop.item_id ? (
this.props.load_cancel ? (
<button onClick={this.props.handle_load_start}>start</button>
) : (
<button onClick={this.props.handle_load_cancel}>Cancel</button>
)
) : null
Upvotes: 4
Reputation: 5246
You can check this.props.load_cancel
and if it's true render the start button otherwise render the cancel button
{props.item_id && (this.props.load_cancel? <button onClick=
{this.props.handle_load_start}>start</button> :
<button onClick={this.props.handle_load_cancel}>Cancel</button>)}
Upvotes: 2