Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ternary operator in the render method in reactjs?

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.

like image 680
stackoverflow_user Avatar asked Nov 25 '25 02:11

stackoverflow_user


2 Answers

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
like image 87
Yury Tarabanko Avatar answered Nov 27 '25 16:11

Yury Tarabanko


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>)}
like image 44
Prithwee Das Avatar answered Nov 27 '25 15:11

Prithwee Das



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!