I wanna do a React site that allows the user to enter a number into an input
and when I click the button Verificar
the function Aleatorio
is called. This function has a JavaScript script that render a random number and check if the user hits the number.
But when I enter a number and click on the button, nothing happens.
I think the if statement is being disregarded, ’cause every other thing in the code is perfect.
Here’s the code
export function Main() {
return(
<>
<h1>Seja bem vindo a loteria, carregue <a>aqui</a> para conhecer as regras</h1>
<h2>Introduza um número de 0 a 10 na caixa abaixo</h2>
<input type="number" placeholder="Número" />
<input type="button" value="Validar" onClick={Aleatorio} />
<p id="res">yooo</p>
</>
)
}
function Aleatorio(num = document.getElementById('nmb-num'))
{
let x = Number(num)
let random = Math.floor(Math.random() * (10 - 0 + 1) + 0)
if (num== random){
window.alert('Parabéns, acertaste!')
} else if (num < random){
window.alert('Tás quase, tente um número maior')
}
if (num > random){
window.alert('Tás quase, tente um número menor')
}
}
3
Answers
You should use state to store the input’s value.
The main problem in your script is in the argument of the callback function
Aleatorio
.In React, the callback function used for the prop
onClick
takes by default an argument which is the event (the click) and not a DOM element (like in your casedocument.getElementById('nmb-num')
). Since in your scenario you won’t need to use the event argument, then you don’t have to pass anything to your function.There are 2 other issues that your code was having:
1) You should access the value field of the input element to get the number of the user. So for instance it should be:
2) You forgot to add the relevant id attribute to the input (id="nmb-num")
Complete code:
In the callback function Aleatorio() you have used document.getElementById() which applies to normal DOM. if you want an equivalent function you can use the useRef hook as explained in React Documentation.