React - Render Conditionally from Props

Hello dear friends i hope you doing and coding fine,

I got confused and stacked with this example, from the very beginning because this expression, … for 50/50 odds, use `Math.random() >= .5 , using this i couldn’t complete the code, and started to get frustrated and couldn’t find sense for React , i had to see the solution to overcome but why the need of mixing too much ? the problem could be solved in one component only .

And about the expression as well, why don’t we use 0 or 1 instead we need to use 0.5 ?
expression = Math.random() > 0.5 ? true : false

Your code so far


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: this.state.counter+1
      }
    });
  }
  render() {
    const expression = Math.random()>= 0.5 ? true: false; // Change this line
    return (
      <div>
        <button onClick={this.handleClick}>Play Again</button>
        {/* Change code below this line */}
<h1> 
{expression? "You Winn" : "You lose"}
</h1>
        {/* Change code above this line */}
        <p>{'Turn: ' + this.state.counter}</p>
      </div>
    );
  }
}

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36

Challenge: React - Render Conditionally from Props

Link to the challenge:

From the online definition of Math.random we see:

The Math.random() function returns a floating-point, pseudo-random number that’s greater than or equal to 0 and less than 1,

We cannot use 1 as Math.random will never give 1. Also you want a half-half probability so that means you want to split the range of available random values in half as well. Therefore you should use >= 0.5 (not just > 0.5) to get an equal distribution of probability.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.