freeCodeCamp Challenge Guide: Render Conditionally from Props

Render Conditionally from Props


Hints

Hint 1

Use Math.random() with the ternary operator to return true or false.

Hint 2

Render the Results component within the GameOfChance component. Pass the variable expression to Results as a prop called fiftyFifty.

Hint 3

Correct the counter property of the state so that the handleClick() method increments it by 1.


Solutions

Solution 1 (Click to Show/Hide)

In render() method use Math.random() as mentioned in the challenge description and write a ternary expression to return true if Math.random() returns a value >= 0.5, and false otherwise.

class Results extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <h1>
      {this.props.fiftyFifty ? "You Win!" : "You Lose!"}
      </h1>
    )
  };
};

class GameOfChance extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 1
    }
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => {
      // Complete the return statement:
      return {
        counter: prevState.counter + 1
      }
    });
  }

  render() {
    const expression = Math.random() >= 0.5;
    return (
      <div>
        <button onClick={this.handleClick}>Play Again</button>
        { /* change code below this line */ }
        <Results fiftyFifty={expression} />
        { /* change code above this line */ }
        <p>{'Turn: ' + this.state.counter}</p>
      </div>
    );
  }
};
44 Likes