Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
Generating random array in reactjs

I'm trying to generate a specific size random array in reactjs everytime a user hits a button. The code to generate the array is the following:

const generateArray = (arraySize: number): number[] => {
  return [...Array(arraySize)].map(() => ~~(1 + Math.random() * 100) );  
}

This code seems to work when I test it separately. I can call it how many times I want and it will still work.

However when I use this function with a simple reactjs code it will only work for the first time and then it will return a one element array all the other times the user clicks the button.

class App extends React.Component<IProps, IState> {
  constructor(props: IProps) {
    super(props);
    this.state = {
      arraySize: 30,
      array: generateArray(30)
    };
  }
  
  resetArray = (size: number) => {
    this.setState({
      ...this.state,
      array: generateArray(size)
    })
  }

  handleArraySizeChange = (event: any) => {
    this.setState({arraySize: event.target.value});
  }

  render() {
    return (
      <div className="App">
        <input type="range" min="0" max="100" value={this.state.arraySize} onChange={this.handleArraySizeChange}/>
        <button onClick={() => this.resetArray(this.state.arraySize)}>Generate new array</button>
        {this.state.array.map( (el: any) => 
            <div >
              {el}
            </div>
        )}
      </div>
    );
  }
}
export default App;

The only way to make this code works is to change the generateArray function like this:

const generateArray = (arraySize: number): number[] => {
  var array = [];
  for(let i = 0; i < arraySize; i++)
    array.push(~~(1 + Math.random() * 100));
  return array;
}

Could someone help me understand why the first generateArray function is not working?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I tried using the above function in this URL: https://codesandbox.io/s/brave-bardeen-7slbh?file=/src/App.js

I console logged the array & I can see it's working as expected

about 4 years ago · Juan Pablo Isaza Denunciar

0

The issue is event.target.value gives a string and you are passing that as a size which is supposed to be a number. To fix simply convert that into a number.

handleArraySizeChange = (event: any) => {
  this.setState({arraySize: Number(event.target.value)});
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda