How do I get two numbers typed by the user via form and send to a function that will pick a random value between them in React

Asked

Viewed 42 times

-1

At the moment my code is like this, but it’s very messy, although I think it’s possible to understand the intention.

The question is: How do I get two numbers typed by the user via form and send to a function that will pick a random value between them in React?

import React from 'react';
import '../styles/pagescss/aleatorio.css';

function Aleatorio() {

  function refreshPage() {
    window.location.reload(false);
  }

  function declararVariavel() {
    var max = document.getElementById('max').value;
    var min = document.getElementById('min').value;
  }

  function getRandomInt(max, min) {
    return Math.floor(Math.random() * (max - min)) + min;
  }

  const Numeros = () => {
    return getRandomInt();
  };

  return (
    <div id="corpo">

      <h2 id="titulo">JavaScript Math Random</h2>

      <p id="texto">A expressão: <br /> Math.floor(Math.random() * (max - min + 1)) + min <br />retorna um numero inteiro aleatorio</p>

      <form id="form">
        <label id="label">
          <input type="number" id="max" placeholder="Máximo" />
          <input type="number" id="min" placeholder="Mínimo" />
        </label>

        <input onclick="declararVariavel()" type="submit" id="botao" placeholder="Enviar" />
      </form>



      <div id="botao">
        <button onClick={refreshPage}>Gerar Números</button>
      </div>

      <div id="numeroCorpo">
        <div id="number">
          <Numeros />
        </div>
      </div>

    </div>
  );


}

export default Aleatorio;

I want to take the information typed in the two inputs (min and max) and put into function getRandomInt()

  • Observed the response?

1 answer

0

I don’t know where you’re learning , because, is doing everything wrong, using commands that should not use and not using the state resources of the local component, minimal example to solve your problem:

function Aleatorio(){
  const [min, setMin] = React.useState(0);
  const [max, setMax] = React.useState(0);
  const [ale, setAle] = React.useState(0);
  function handleSubmit(e){
    e.preventDefault();
    setAle(getRandomInt(max, min));            
  }
  function getRandomInt(max, min) {
    return Math.floor(Math.random() * (max - min)) + min;
  }
  const Numeros = () => {
    return (
      <div className="mt-3 text-center">
        <h1>{ale}</h1>
      </div>
    )  
  };  
  return (
    <div className="container">
      <form onSubmit={handleSubmit}>
      <div className="row">
        <div className="col-6">
          <div className="form-group">
          <label>Min: </label>          
          <input 
            className="form-control"
            type="number" 
            value={min} 
            onChange={e => setMin(parseInt(e.target.value))}
           />
           </div>
        </div>
        <div className="col-6">
          <div className="form-group">
          <label>Max:</label>          
          <input
            className="form-control"
            type="number" 
            value={max} 
            onChange={e => setMax(parseInt(e.target.value))}
          />
          </div>
        </div>
        <div className="col-12 mt-3">
          <button type="submit" 
            class="btn btn-primary btn-block"
            disabled={isNaN(min) || isNaN(max) || (max === min) || (min > max)}
          >
            Gerar Números
          </button>
        </div>
      </div>
      </form>
      <Numeros />
    </div>
  )
}


ReactDOM.render( <Aleatorio/> , document.getElementById('root'));
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root">Carregando ...</div>

3 state variables were created that are part of this component, kept min, max and ale (minimum value, maximum value and random value) where the changes of their respective <input/> where at the time of typing the values will also be changed.

Pressing the button with label Generate Numbers the form is submitted and intercepted to not happen the common form submission event and after this command, generate the random value for the variable ale.

All this was used only commands from library and there’s a lot of stuff on the Internet that can help you, for example:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.