3

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.

flppv
  • 4,111
  • 5
  • 35
  • 54

3 Answers3

4

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
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
2

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>)}
Prithwee Das
  • 4,628
  • 2
  • 16
  • 28
0

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.

Razvan Pop
  • 198
  • 9