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

118
Views
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 answers
Answer question

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 Report

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 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!