BearCola
4/18/2019 - 9:14 PM

React - ternary operator or conditional in jsx to include html with react

// in jsx

class NumberPicker extends React.Component {
  render() {
    const num = getNum();
    return (
      <div>
        <h1>Your number is {num}</h1>
        <p>{num === 7 ? "Congrats!" : "Unlucky!"}</p>
        {num === 7 && (
          <img src="https://i.giphy.com/media/nXxOjZrbnbRxS/giphy.webp" />
        )}
      </div>
    );
  }
}

// conditional 
class NumberPicker extends React.Component {
  render() {
    const num = getNum();

    let msg;
    if (num === 7) {
      msg = (
        <div>
          <h2>CONGRATS YOU WIN!</h2>
          <img src="https://i.giphy.com/media/nXxOjZrbnbRxS/giphy.webp" />
        </div>
      );
    } else {
      msg = <p>Sorry You Lose!</p>;
    }

    return (
      <div>
        <h1>Your number is {num}</h1>
        {msg}
      </div>
    );
  }
}