1

I'm trying to do a random number generator with React (I'm new on it) that has an min and max input but it doesn't work well, it's generating random numbers but not between max and min

import React, { useState } from 'react';
import './style.css';

export default function PaginaInicial() {
  const [numeroAleatorio, setNumeroAleatorio] = useState(0);
  const [ValorMax, setValorMax] = useState(100);
  const [ValorMin, setValorMin] = useState(0);

  function BotaoMax() {
    var ValorMaximo = document.getElementById('max').value
    setValorMax(ValorMaximo);

  };
  function BotaoMin() {
    var ValorMinimo = document.getElementById('min').value
    setValorMin(ValorMinimo);
  };
  function gerarNumero() {
    const newNumber = parseInt(Math.random() * (ValorMax - ValorMin)) + ValorMin;
    setNumeroAleatorio(newNumber);
    if (ValorMax < ValorMin) {
      alert('Max value should be higher than Min value')
      setNumeroAleatorio('Error')
    };
  };

  return (
    <div className="conteudo-centralizado">
      <h3>Random Number:</h3>
      <div className="divNum">
      </div>

      <div>
        <input type="number" id='min' min='1' max='9999' placeholder="Número Mínimo" onChange={BotaoMin} />
        <input type="number" id='max' min='1' max='9999' placeholder="Número Máximo" onChange={BotaoMax} />
      </div>
      <h1>{numeroAleatorio}</h1>

      <div className='area-botao'>
        <label>
          Click on the following button to get a random number:
        </label>

        <button onClick={gerarNumero}>
          Generate Number
        </button>
      </div>
    </div>
  );
}

Also I'm from Brazil so some words are in portuguese, sorry

Thiago MM
  • 11
  • 4

4 Answers4

0

named functions in react are not reactive , that is they are evaluated once , if that function is referencing a value outside the functions scope it would only use the initial value of that variable if the variable is updated the function would not be re-initialized

so genrarNmero function

function gerarNumero() {
  const newNumber = parseInt(Math.random() * (ValorMax - ValorMin)) + ValorMin;
  setNumeroAleatorio(newNumber);
  if (ValorMax < ValorMin) {
    alert('Max value should be higher than Min value');
    setNumeroAleatorio('Error');
  }
}

would always have ValorMax and ValorMin to be 100 and 0

you can resolve this by passing in ValorMax and ValorMin as an argument to the function

function gerarNumero(ValorMax, ValorMin) {
  const newNumber = parseInt(Math.random() * (ValorMax - ValorMin)) + ValorMin;
  setNumeroAleatorio(newNumber);
  if (ValorMax < ValorMin) {
    alert('Max value should be higher than Min value');
    setNumeroAleatorio('Error');
  }
}

or you can use the useCallback hook for react which would re-initialize a function if the dependencies changes

const gerarNumero = useCallback(() => {
  const newNumber = parseInt(Math.random() * (ValorMax - ValorMin)) + ValorMin;
  setNumeroAleatorio(newNumber);
  if (ValorMax < ValorMin) {
    alert('Max value should be higher than Min value');
    setNumeroAleatorio('Error');
  }
}, [ValorMax, ValorMin]);
Kartikey
  • 4,516
  • 4
  • 15
  • 40
  • and since you are using react instead of using a query selector to update the state of your `ValorMax` and `ValorMin` you can just pass in a function that takes the event to the onChange property of your input element, eg ` setValorMin(e.target.value)} />` – onifade boluwatife Sep 23 '21 at 22:19
0

You should add Math.floor() function in your gerarNumero() function.

const newNumber = parseInt(Math.floor(Math.random() * (ValorMax - ValorMin) + ValorMin));

Please check following link https://futurestud.io/tutorials/generate-a-random-number-in-range-with-javascript-node-js

0

You should convert ValorMin to number, because 1 + '1' = '11' in js.

Try this

const newNumber = parseInt(Math.random() * (ValorMax - ValorMin)) + +ValorMin;
Andriy Lozynskiy
  • 2,444
  • 2
  • 17
  • 35
0

CodeSandbox

You need to convert ValorMaximo and ValorMinimo from strings into numbers.

import React, { useState } from 'react';
import './style.css';

export default function PaginaInicial() {
  const [numeroAleatorio, setNumeroAleatorio] = useState(0);
  const [ValorMax, setValorMax] = useState(100);
  const [ValorMin, setValorMin] = useState(0);

  function BotaoMax() {
    var ValorMaximo = document.getElementById('max').value
    // Convert to number
    setValorMax(Number(ValorMaximo));

  };
  function BotaoMin() {
    var ValorMinimo = document.getElementById('min').value
    // Convert to number
    setValorMin(Number(ValorMinimo));
  };
  function gerarNumero() {
    const newNumber = parseInt(Math.random() * (ValorMax - ValorMin)) + ValorMin;
    setNumeroAleatorio(newNumber);
    if (ValorMax < ValorMin) {
      alert('Max value should be higher than Min value')
      setNumeroAleatorio('Error')
    };
  };

  return (
    <div className="conteudo-centralizado">
      <h3>Random Number:</h3>
      <div className="divNum">
      </div>

      <div>
        <input type="number" id='min' min='1' max='9999' placeholder="Número Mínimo" onChange={BotaoMin} />
        <input type="number" id='max' min='1' max='9999' placeholder="Número Máximo" onChange={BotaoMax} />
      </div>
      <h1>{numeroAleatorio}</h1>

      <div className='area-botao'>
        <label>
          Click on the following button to get a random number:
        </label>

        <button onClick={gerarNumero}>
          Generate Number
        </button>
      </div>
    </div>
  );
}
khan
  • 1,466
  • 8
  • 19
  • Thank you! Had to use `const newNumber = parseInt(Math.random() * (ValorMax - ValorMin)) + +ValorMin;` as well as Andriy told – Thiago MM Sep 23 '21 at 22:47
  • No problem. And you don't need to use the unary operator, the `+` before `ValorMin`, since `ValorMin` is already a number. See the CodeSandbox in the answer. – khan Sep 23 '21 at 22:48
  • I prefere `+` becouse its shorter and behave almost like `Number()`. `setValorMax(+document.getElementById('max').value)` – Andriy Lozynskiy Sep 23 '21 at 23:03
  • Converting a string into a number using `Number()` vs. unary `+` is apart from the issue that @ThiagoMM was facing. – khan Sep 23 '21 at 23:08