Home > Enterprise >  Generating random array in reactjs
Generating random array in reactjs

Time:11-30

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related