How to access to a state in the render part with for loop?

Viewed 37

I have an array in the state and I want to render this array one by one with for loop. I can't figure out how to get the length of array, any idea? Thank you for the help. here is my code:

this.state = {
    array: []
}
// here is the function to write data into array
render(){
   return(
         <div>
            for(let i = 0; i < this.state.array.length; i++) { //this line doesn't work, error with length part
               <p> {this.state.array[i]}</p> // this line will work if I wirte outside of loop
            }
          </div>
    )
}
2 Answers

for-loop constructs don't work in JSX like they do in javascript, since you aren't returning anything in the loop.

Just use array.prototype.map to map state.array to the JSX you want to render for each element within the array. By mapping the state you needn't worry about the array length, the map function handles it.

this.state = {
    array: []
}

render() {
  return (
    <div>
      {this.state.array.map((el, i) => (<p key={i}>{el}</p>))}
    </div>
  );
}

Lists and Keys - Official docs for rendering lists of data

You should do something like this:

render(){
   return(
         <div>
         {
              this.state.array.map((element, index) => {
                  return (
                        <p key={`key-${index}`}>{element}</p>
                  );
              })
         }
          </div>
    )
}

Don't forget the key prop when rendering multiple components in a loop in React.

Related