Koala7
Koala7

Reputation: 1414

React Conditional rendering mapping an array

I have reproduced my scenario in this codesandbox

I have an array of tags of 5 elements

const tagsList = ["Covid 19", "Business", "Energy", "Sport", "Politics"];

I am mapping for each tag my Chip component

  {tagsList.map((tag) => (
    <Chip label={tag} />
  ))}

I want to say that if the taglist length is bigger than 2 ( which is my case in the codesandbox ) to show me the chip with the tags left, which are 3 ( length - 2 ).

How can i make in the same map function? Is there an other way?

Upvotes: 0

Views: 770

Answers (3)

ImInYourCode
ImInYourCode

Reputation: 605

You can do this if you don't mind not starting at position 0:

<div className={classes.root}>
      {(tagsList.length > 2 ? tagsList.slice(3, 5) : tagsList).map((tag) => (
        <Chip label={tag} />
      ))}
      {tagsList.length > 2 && <Chip label={tagsList.length - 2} /> }
</div>

Upvotes: 1

MarcSanchez
MarcSanchez

Reputation: 101

You can collect index (position of element in list) in the map function and act according to your needs, if I understand it wright mayby you could do something like this :

return (
    <div className={classes.root}>
      {/* Change to shortTagsList for check the shortest */}
      {tagsList.map((tag, index) => {
        let length = tagsList.length;
        console.log(length);
        return (
          (length > 2 && index > 2 && <Chip label={tag} />) ||
          (length <= 2 && <Chip label={tag} />)
        );
      })}
    </div>
  );

codesandbox

Upvotes: 1

Sarun UK
Sarun UK

Reputation: 6766

You can use tagsList.slice(2) if the list size is greater than 2.

export default function OutlinedChips() {
  const classes = useStyles();

  const tagsList = ["Covid 19", "Business","Energy", "Sport", "Politics"];

  return (
    <div className={classes.root}>
      {(tagsList.length > 2 ? tagsList.slice(2) : tagsList).map((tag) => (
        <Chip label={tag} />
      ))}
    </div>
  );
}

Working code - https://codesandbox.io/s/material-demo-forked-31f2w?file=/demo.js

Upvotes: 3

Related Questions