I try to convert vanilla javaScript into React but I was unable to get the correct result.
Here is the vanilla javaScript code:)
var minimum = 1;
var maximum = 100;
var int1 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
var int2 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
document.getElementById('question').innerHTML = int1 + " " + "+" + " " + int2;
var qanswer = int1 + int2;
function fire() {
var uanswer = document.getElementById('answer').value;
if (uanswer == qanswer) {
alert("Nice math skills! Refresh the page to play again!");
} else {
alert("WRONG! Don't snooze during math class!")
}
}
This is the React code :)
export default function App() {
const [inputValue, setInputValue ] = useState('')
let minimum = 1;
let maximum = 10;
let int1 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
let int2 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
var qanswer = int1 + int2;
const handleChange = (e) => {
setInputValue(e.target.value)
}
const handleAnswer = () => {
if(qanswer === inputValue) {
alert('You won')
} else {
alert('You lose')
}
}
return (
<div className="App">
<h1>Math Game</h1>
<h2>{`${int1} + ${int2}`}</h2>
<input value={inputValue} onChange={handleChange}/>
<button onClick={handleAnswer}>Answer</button>
</div>
);
}
Now the problem is here when I type the answer in the input field my random number value is changed.