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({
      counter: this.state.counter + 1 // change code here
    });
  }
  render() {
    const expression = Math.random() >= 0.5 ? true : false
    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>
    );
  }
};
14 Likes