Search code examples
javascriptreactjsfunctionjsxreact-component

Return JSX from component method to render method


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!


Solution

  • 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
      )
    }