Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading