Showing elements based on ternary operator

Viewed 85

I'm trying not to render part of my code. I want to render it only when answer is correct/not correct. At the beginning only question and answers should be displayed. React renders false argument "you are wrong". State is set to null. I checked and null doesnt equal false nor true. Why does it renders anything? How to not render anything until user chooses wrong/correct answer? Code:

export default class QuoteApp extends Component {
  constructor(props) {
    super(props)

    this.state = {
       index: 0,
       isCorrect: null
    }
  }

  confirmAnswer = () => {
      this.setState({
          index: this.state.index + 1
      })
  }

  handleClick = (e, index) => {
    if (e.target.textContent === data[index].name) {
      this.setState({
        isCorrect: true
      }) 
      } else {
        this.setState({
          isCorrect: false
        })
    }
  }

  render() {
      const { index, isCorrect } = this.state
      console.log(this.state)
    return (
      <div className="QuoteApp">
        <div className={ (this.state.isCorrect ? 'hide' : '') }>
          <Quote index={index}/>
          <Answers index={index}
                 handleClick={this.handleClick}
                 />
        </div>
        {isCorrect ?
        <h1>you're right</h1>
        :
        <h1>you're wrong</h1>}
        <button onClick={this.confirmAnswer}>Confirm</button>
      </div>
    )
  }
}

I want

you're right : you're wrong to be gone till user interaction

2 Answers

Using && operator. You will see you're right or wrong only on user interaction

{isCorrect !== null && isCorrect && 
        <h1>you're right</h1>}
{isCorrect !== null && !isCorrect && 
        <h1>you're wrong</h1>}

Do something like below to hide Quote/Answer when user chooses answer

Using && operator

    {isCorrect === null && <div className={ (this.state.isCorrect ? 'hide' : '') }>
      <Quote index={index}/>
      <Answers index={index}
             handleClick={this.handleClick}
             />
    </div>}

OR ternary operator

 {isCorrect === null ? <div className={ (this.state.isCorrect ? 'hide' : '') }>
      <Quote index={index}/>
      <Answers index={index}
             handleClick={this.handleClick}
             />
    </div> : null}

You can write like this:

{ isCorrect !== null && 
  ( isCorrect ? <h1>you're right</h1> : <h1>you're wrong</h1> )
  || '' // To make sure we don't print boolean value in the UI
}

The && condition will will satisfy the isCorrect return value. If it is null, then it will not go ahead. We're wrapping them in a parentheses because we would like to execute the code inside that only if isCorrect is not null.

Related