title: ReactJS 'guess the number game'
body: <p>I've created a very simple 'Guess The Number' game with ReactJS which seems to be working well except it executes when the user changes the input and not on the button click as I expected.</p>
  
  <p>What am i doing wrong?</p>
  
  <p>Demo: <a href="https://codesandbox.io/s/guess-the-number-game-82z1n" rel="nofollow noreferrer">https://codesandbox.io/s/guess-the-number-game-82z1n</a></p>
  
  <p>Code</p>
  
  <pre><code>import React, {useState} from 'react';
  
  let randomNumber = Math.round(Math.random() * 10);
  
  const GuessTheNumber = () =&gt; {
  
  const [value, setValue] = useState('');
  const onChange = e =&gt; setValue(e.target.value);
  let results = "";
  
  const onClick = () =&gt; { 
      // check users guess against randonNumber
      const userGuess = value;
      if (userGuess == "") return null;
      if (userGuess == randomNumber ) return &lt;p className="alert alert-success"&gt;Correct!&lt;/p&gt;;
      if (userGuess &gt; randomNumber) return &lt;p className="alert alert-warning"&gt;Too high, guess again&lt;/p&gt;;
      if (userGuess &lt; randomNumber) return &lt;p className="alert alert-warning"&gt;Too low, guess again&lt;/p&gt;        
  }
  
  results = onClick(value)
  
  return (
      &lt;&gt;
          &lt;h2&gt;Guess The Number game&lt;/h2&gt;
          &lt;p className="lead"&gt;Guess a number between 1 and 10.&lt;/p&gt;
          &lt;input value={value} type="number" onChange={onChange}/&gt;
          &lt;button type="submit" onClick={onClick}&gt;GUESS&lt;/button&gt;
          &lt;br /&gt;&lt;br /&gt;
          {results}
  
      &lt;/&gt;
  )
  }
  
  export default GuessTheNumber;
  </code></pre>