skip to Main Content

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


  1. You should use state to store the input’s value.

    import { useState } from 'react';
    export function Main() {
        const [val, setVal] = useState('');
        function Aleatorio() {
            const x = +val;
            const random = Math.random() * 11 | 0;
            if (x < random) alert('Tás quase, tente um número maior');
            else if(x > random) alert('Tás quase, tente um número menor');
            else alert('Parabéns, acertaste!');
        }
        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" value={val} onChange={e => setVal(e.target.value)} />
                <input type="button" value="Validar" onClick={Aleatorio} />
                <p id="res">yooo</p>
            </>
        );
    }
    
    Login or Signup to reply.
  2. 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 case document.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:

    document.getElementById("nmb-num").value
    

    2) You forgot to add the relevant id attribute to the input (id="nmb-num")

    Complete code:

    export default function Main() {
      function Aleatorio() {
        let x = parseInt(document.getElementById("nmb-num").value);
        let random = Math.floor(Math.random() * (10 - 0 + 1) + 0);
        if (x === random) {
          window.alert("Parabéns, acertaste!");
        } else if (x < random) {
          window.alert("Tás quase, tente um número maior");
        }
        if (x > random) {
          window.alert("Tás quase, tente um número menor");
        }
      }
      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 id="nmb-num" type="number" placeholder="Número" />
          <input type="button" value="Validar" onClick={Aleatorio} />
          <p id="res">yooo</p>
        </>
      );
    }
    
    Login or Signup to reply.
  3. 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.

    import React, { useRef } from 'react';
    
    export function Main() {
      const numRef = useRef(null);
    
      return (
        <>
          <h1>
            Seja bem-vindo à loteria, carregue <a href="#">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" ref={numRef} />
          <input type="button" value="Validar" onClick={Aleatorio} />
          <p id="res">yooo</p>
        </>
      );
      
      function Aleatorio(){
        let x = Number(numRef.current.value);
        let random = Math.floor(Math.random() * (10 - 0 + 1) + 0);
        
        if (x === random) {
          window.alert('Parabéns, acertaste!');
        } else if (x < random) {
          window.alert('Tás quase, tente um número maior');
        } else if (x > random) {
          window.alert('Tás quase, tente um número menor');
        }
      };
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search