0

I'm still new to React. I'm trying to render a jsx under a condition defined in another method under my class component like so:

isWinner = () => {
 let userVotesCount1 = this.state.user1.userVotesCount;
 let userVotesCount2 = this.state.user2.userVotesCount;
 if (userVotesCount1 > userVotesCount2) {
   userVotesCount1++;
   this.setState({ user1: { userVotesCount: userVotesCount1 } });
   return (
     <h3>Winner</h3>
   );
 }
 userVotesCount2++;
 this.setState({ user2: { userVotesCount: userVotesCount2 } });
 return (
   <h3>Loser</h3>
 );}

and i'm calling this method inside the render method

<Dialog
   open={open}
   onRequestClose={this.onClose}
      >
 <div>
   <isWinner />
 </div>
 </Dialog>

already tried to use replace <isWinner /> for {() => this.isWinner()}and I never get the return from the method. What I am doing wrong? Since I'm dealing with state here I wouldn't know how to do this with outside functions. For some reason this function is not being called ever. Please help!

  • Possible duplicate of [How to Call a Function inside a Render in React/Jsx](https://stackoverflow.com/questions/40298136/how-to-call-a-function-inside-a-render-in-react-jsx) – Agney Apr 21 '18 at 03:08

1 Answers1

1

You're almost there. What you want to do is use the method to set a flag, and then use the flag in the render method to conditionally render.

constructor(props) {
  ...
  this.state = {
    isWinner: false,
    ...
  }
}
isWinner() {
  ...,
  const isWinner = __predicate__ ? true : false;
  this.setState({
    isWinner: isWinner
  });
}

render() {
  const { isWinner } = this.state;
  return isWinner ? (
    // jsx to return for winners
  ) : (
    // jsx to return for lossers
  )
}
Kyle Richardson
  • 5,567
  • 3
  • 17
  • 40
  • This actually rendered the JSX, however it only renderes loser, no matter what I choose. Besides, the state has 2 users wich have 2 more properties on them. I know that setState is async and there's a lot of them in this code. Shouldn't there be a timeout or something. If so, how to do it? – Marcel Paschoal Apr 21 '18 at 04:44
  • You've got too much going on with not enough shown in the example to give you a good answer without just writing the code for you. Why don't you make a [code sandbox](https://codesandbox.io/s/new) of your project and link it here. I will help you debug it tomorrow if you haven't been helped or figured it out by then. – Kyle Richardson Apr 21 '18 at 05:48
  • https://codesandbox.io/s/2m4m7x2yn There it is. I tried your solution but i think it's something related to setState method. – Marcel Paschoal Apr 21 '18 at 18:14
  • Nevermind there was a problem in my logic. Its all solved, thanks for the help. – Marcel Paschoal Apr 21 '18 at 20:15