Home > Software engineering >  React renders only one component from an array
React renders only one component from an array

Time:11-04

Here's the problem with iterating over the components as array elements, I guess. I tried many iteration methods for loop, .forEach() and .map(). The some result was came only from the first one. It was rendered only one component from the array, when famous methods .forEach() and .map() wasn't rendered nothing at all.

I logged to the console the value of iterator variable from the above for loop and it wasn't incremented at all, it was 0, when the max count is 10.

Here's the code:

const renderState = () => {
    if (loading) {
      // When the users objects are loading from the server:
      return <p>Loading...</p>;
    } else if (hasErrors) {
      // When some loading-error occured:
      return <p>Can not load the page.</p>;
    } else {
      // And when loading was successfully finished, rendering all of them:
      for (let i = 0; i < users.length; i  ) {
        return <ProfileCard key={users[i].id} user={users[i]} />
      }
    }
  };

CodePudding user response:

I think only 1 item is rendering because you are returning something. "The return statement ends function execution and specifies a value to be returned to the function caller." - MDN docs

I've got a list in my app and that goes:

{orders.map((order) => ( 
    <Order key={order.Oid} data={order}/>
))}

So, try removing the return statement. And try it with .map

EDIT:

in the else statement:

return {users.map((user) => <ProfileCard />)}

CodePudding user response:

The solution is to put the iterating function (for this case it's the .map() method) into the direct return statement of the React component:

return (
    <div>
      {
        users.map((user) => (
          <ProfileCard key={user.id} user={user} />
        ))
      }
    </div>
  );

  • Related