Problems with returning an if statement in React with different jsx components

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

>Solution :

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

Leave a Reply