nCardot
nCardot

Reputation: 6587

Render multiple components with a single ternary operator

If currentProfiles.length > 0, I'd like to map over an array named profiles and render a profile component for each profile, and render a pagination component below the profiles. I tried this with a single ternary operator, but this results in only the pagination component being rendered.

    {currentProfiles.length > 0 ? (
      (currentProfiles.map(profile => (
        <ProfileItem key={profile._id} profile={profile} />
      )),
      (
        <Pagination
          profilesPerPage={profilesPerPage}
          totalProfiles={profiles.length}
        />
      ))
    ) : (
      <Spinner />
    )}

If I use two separate ternary operators, I get the list of profiles and pagination as expected, but can I do both things with a single conditional operator?

Upvotes: 1

Views: 1184

Answers (2)

user10593684
user10593684

Reputation:

Your code just needs some restructuring. If you wrap the mapped profiles and pagination components in a parent fragment or other element, it's easy. Note, too, that the first example below still retains the ternary, as requested.

  return (
    <div className="App">
      {currentProfiles.length ? (
        <>
          {currentProfiles.map(p => (
            <Profile {...p} />
          ))}
          <Pagination profilesPerPage={2} totalProfiles={totalProfiles} />
        </>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );

However, you have a few options aside from wrapping them in a non-rendered Fragment or its shorthand derivative. You could also use an actual element, such as a div. Or even omit the parent entirely and place your logic within an array, as in:

<div className="App">
  {currentProfiles.length ? [
    currentProfiles.map(p => (
      <Profile {...p} />
    )),
    <Pagination profilesPerPage={2} totalProfiles={totalProfiles} />
  ] : <p>Loading...</p>}
</div>

Always remember that, unless you utilize the second approach, you'll need to ensure siblings share a common parent.

Working example.

Upvotes: 1

Silvino Escalona
Silvino Escalona

Reputation: 321

You can use an array or a fragment https://reactjs.org/docs/fragments.html

{currentProfiles.length > 0 ? (
     <>
      currentProfiles.map(profile => (
        <ProfileItem key={profile._id} profile={profile} />
      )

        <Pagination
          profilesPerPage={profilesPerPage}
          totalProfiles={profiles.length}
        />
      </>
    ) : (
      <Spinner />
    )}

Upvotes: 0

Related Questions