0

So my app takes three random values from an array inside defaultProps, and displays these inside divs in the return JSX and sets the values of three properties in state.

I need to change the state depending on what these random values are (if random1 === random2 || random2 === random3). I have put ternary operators inside console.logs inside the main div and they output exactly what I want. However, when I attempt to create a function with an if else statement in the same place, it does not change the state. I'm imagining this is an issue with scope?

Any help much appreciated.

This is the code I have tried to use:

this.state = { 
    fruit1: "", fruit2: "", fruit3: "", 
    rolling: false, win: false, bigWin: false, 
    bankAccount: 0 
  };

...

render (
        <div class="main-div">
          {function winCheck() {
        if (this.state.fruit1 === this.state.fruit2) {
          this.setState({ win: true })
        } else {
          this.setState({win: false})
        }
      }}
      </div>
      )
HarryW
  • 155
  • 2
  • 7

1 Answers1

1

You can't do that inside render. You should make a function that returns true or false depending the state values.

const hasWon = () => {
    const { fruit1, fruit2 } = this.state;
    return fruit1 === fruit2;
}

Then in the render:

render (
    <div class="main-div">
      {this.hasWon() ? /* WON COMPONENT */ : /* LOOSE COMPONENT */}
    </div>
  )
Jon
  • 166
  • 6
  • Thanks for the answer Jon. Just to be clear; if fruit1 === fruit2, hasWon will become truthy? So inside hasWon, I could include 'hasWon ? this.setState({win : true}): null'? Sorry, I'm still learning! – HarryW Jun 19 '20 at 10:13
  • No problem, Harry, everyone has ever learn React. Yes, you could do that, but then, in the render part you should replace this.hasWon() for this.state.win. – Jon Jun 19 '20 at 10:21