Home > Software design >  Problems with returning an if statement in React with different jsx components
Problems with returning an if statement in React with different jsx components

Time:11-09

I want to get the button printed out and whenever it is clicked to change the property searching game to the opposite (if its false - true) and print out the other button. Right now not even a button appears (if its in the jsx code after the return it prints the button but doesn't change it on click). Any ideas how can I write it down?

let searchingGame = false;

    const isSearchingForGame = () => {
        searchingGame = !searchingGame;

        if (isSearchingForGame == true)
        {
            return (<button onClick={isSearchingForGame} className="find-match">Find Match</button>)
        }

        else
        {
            return (<button onClick={isSearchingForGame} className="find-match">Searching for a Match</button>)
        }
    }

 return (
        <div className="look-ranked-container">
 <div className="time-searching">Searching: 00:23 min</div>
                        {isSearchingForGame}
    </div>
    )
}

CodePudding user response:

  • The function is not called, changed it to : {isSearchingForGame()}
  • The searchingGame should be a hook (eg useState)
  • The double return can be simplified by setting the text and then a single return

Demo:

const { useState, useEffect } = React; 

function App() {
    const [searchingGame, setSearchingGame] = useState(false);

    const toggleIsSearching = () => setSearchingGame(!searchingGame);

    const getContent = () => {    
        const text = (searchingGame)
            ? 'Find Match'
            : 'Searching for a Match'

        return (<button onClick={toggleIsSearching} className="find-match">{text}</button>)
    }

    return (
        <div className="look-ranked-container">
            <div className="time-searching">Searching: 00:23 min</div>
            {getContent()}
        </div>
    );
}

const root = ReactDOM.createRoot(document.getElementById("react"));
root.render(<App />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="react"></div>

CodePudding user response:

You should call the function isSearchingForGame like {isSearchingForGame()} and make your variable searchingGame a state in your component with useState.

Also, you can improve this code by adding the function's piece of code inside the jsx code like this:

return (
   <div className="look-ranked-container">
     <div className="time-searching">Searching: 00:23 min</div>
     <button onClick={isSearchingForGame} className="find-match">. 
     { searchingGame ? 'Find Match' : 'Searching for a Match' }</button>
   </div>
)
  • Related