-3

I am a beginner in React js and trying to do some operations.

I want to create an array till the length of any array (particular number) suppose my array length is 10 , then the array should be

my state variables-

 this.state{
 length = 10,
 length_array= []
}

handleClick = () =>{
    this.setState{
    length_array:[1,2,3,4,5,6,7,8,9,10]
}}

I want to display this array in my table header

<Table>
  <tr>
     <th>
         this.state.length_array.map((item, key) =>
         <th>{item.name}</th>
);
     </th>
  </tr>
</Table>

Thanks.

chandra
  • 45
  • 1
  • 1
  • 7

3 Answers3

0

Use normal for loop.

function createArraybyLength(length) {
  let arr = []
  for(let i = 1; i <= length; i++){
    arr.push(i)
  }
  return arr
}
console.log(createArraybyLength(10))
holydragon
  • 6,158
  • 6
  • 39
  • 62
0

In addition to holydragon's answer, without using for loop.

const length = 10;

const arr = Array(10).fill(null).map((item, index) => index + 1);

console.log(arr)
Sachin
  • 169
  • 10
0

do this inside your handleClick

 handleClick = () =>{
     let newArray = []
    for(let i=1; i<=this.state.length; i++){
      newArray.push(i);
    }
    this.setState({
      length_array : newArray
    })
}}
Vikas Singh
  • 1,791
  • 1
  • 14
  • 26