Loop rendering with Arrays in Array in React

Viewed 23

I have an array with arrays in it who look like this : [Array(4), Array(4), Array(1)]

And i want to return the same render for every arrays, i tried something like this :

const articleRender = (array) => {
var index = 0;
var arrayLength = array.length;
for (index; index < arrayLength; index++) {
  return (
    <div>
      {array[index].map((item, i) => {
        return <li key={i}></li>;
      })}
    </div>
  );
}

but the loop just make one iteration.

Thanks everyone.

2 Answers

You should wrap all the array iteration inside the return.

const articleRender = (array) => {
  return (
    <div>
      array.map((item, index) => {
        return (<div>
          {item.map((subitem, i) => {
            return <li key={i}></li>;
          })}
        </div>
      )})
    </div>
  );
}

Because of the return on the first loop of the iteration.

for (index; index < arrayLength; index++) {
  return ( <--- This return is stopping the iteration at index = 0.
    <div>
      {array[index].map((item, i) => {
        return <li key={i}></li>;
      })}
    </div>
  );
}
Related