samedi 21 décembre 2019

use Math.random inside ReactHook

I'm learning react since 2-3 days and I've stumbled into a problem when using Math.random() inside a functional component with React Hook.

Let me explain: suppose I want to code a game where there is a random number generated and the user needs to guess it. I thought about something like that:

function App() {
    const [users, setUsers] = useState("")
    let tbg = Math.floor(Math.random()*100)

    const handleSubmit = () => {
        if(users === tbg) {
            alert("Correct")
        }
        else if(users < tbg) {
            alert("More")
        }
        else {
            alert("Less")
        }
    }
  return (
    <div className="App">
      <h2>Guess the number</h2>
        <h3>(for debug=>) the number is : {tbg} </h3>
        <br/>
        <form onSubmit={handleSubmit}>
            <input type="text" value={users} onChange={e => setUsers(e.target.value)} />
        </form>
    </div>
  );
}

The problem is each time the user input a character/digit the number to be guessed is changed. I thought about a solution by putting the Math random into a function and execute it conditionally. But, I wanted to know if there is a better "a react-hook-way" to do it.

Thank you




Aucun commentaire:

Enregistrer un commentaire