Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

553
Views
Generador de números aleatorios en React

Estoy tratando de hacer un generador de números aleatorios con React (soy nuevo en esto) que tiene una entrada mínima y máxima pero no funciona bien, está generando números aleatorios pero no entre máximo y mínimo

 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> ); }

También soy de Brasil, así que algunas palabras están en portugués, lo siento.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

CódigoSandbox

Debe convertir ValorMaximo y ValorMinimo de cadenas a números.

 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> ); }
about 4 years ago · Juan Pablo Isaza Report

0

las funciones nombradas en reaccionar no son reactivas, es decir, se evalúan una vez, si esa función hace referencia a un valor fuera del alcance de las funciones, solo usaría el valor inicial de esa variable si la variable se actualiza, la función no se reinicializaría

asi genrarNmero la funcion

 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'); } }

siempre tendría ValorMax y ValorMin para ser 100 y 0

puede resolver esto pasando ValorMax y ValorMin como argumento a la función

 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'); } }

o puede usar el enlace useCallback para reaccionar, lo que reinicializaría una función si las dependencias cambian

 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]);
about 4 years ago · Juan Pablo Isaza Report

0

Debe agregar la función Math.floor() en su función gerarNumero().

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

Consulte el siguiente enlace https://futurestud.io/tutorials/generate-a-random-number-in-range-with-javascript-node-js

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!