Home > Blockchain >  Conditional list rendering in React
Conditional list rendering in React

Time:10-28

I have this sidebar component and I want to show the sidebar elements differently if the user is a simple user or is admin.

I have this isManager boolean saved in my state. If isManage is true, I want to loop on the complete links array. If isManager is false, I want to loop on the same array but without the last three elements (a simple array.splice).

But I get confused with JSX syntax and I don't know where to put the condition.

return (
    <div className="flex-item--fill flex--column scops-sidebar-content-container">
      <ul>
        {links.map((link) => (
          <li
            key={link.id}
            className="pad-half--left"
            style={{
              backgroundColor: `${
                activeTabId === link.id ? '#4065d0' : 'var(--color-primary)'
              }`,
            }}
          >
            <button
              className="btn--plain full-width align--left unpad"
              style={{ color: 'white' }}
              onClick={(e) => tabHandler(e, link.id)}
            >
              {link.name}
            </button>
          </li>
        ))}
      </ul>
    </div>
  );

This is my component. Thanks a lot

CodePudding user response:

In addition to Michael P. Bazos answer:

I usually move as much logic as I can outside JSX, because it makes JSX harder to read and you might accidentially change logic by just editing view things.

Thus I would make the decision just before the JSX.

 const linksToRender = isManager ? links : links.slice(0, -3));

 return (
   <div className="flex-item--fill flex--column scops-sidebar-content-container">
     <ul>
       {linksToRender.map((link) => (
         // ....
       ))}
     </ul>
   </div>
);

CodePudding user response:

{(isManager ? links : links.slice(0, -3)).map(link => 
   (...JSX FOR LINK...)
)}

links.slice(0, -3) returns the array minus the last three elements. E.g.:

[1, 2, 3, 4, 5].slice(0, -3) => [1, 2]

Note the we are using slice, and not splice which would mutate the links array as it deletes elements from it.

Note2: I wanted to show the minimal path to reach the answer. Naturally, for better clarity, you can add a line of code and store the result of the condition to a local variable, as suggested by René Link (whose name fits perfectly the answer)

  • Related