0

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?

4
  • I'm not entirely clear on what you're asking for, but it sounds as though you want just a slice of your array. Commented Nov 10, 2020 at 18:55
  • Yes, can you answer with the code, thanks Commented Nov 10, 2020 at 18:57
  • When you say "left" you mean how to position them on the screen, or do you mean to show the first 3 elements ? Commented Nov 10, 2020 at 19:02
  • To show the first 3 elements and put an extra element with only the number 2 ( which are the tags left ) Commented Nov 10, 2020 at 19:04

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Almost perfect thanks, i have just edited tagsList.slice(0, 2) to show the first 2 elements and i need to show a Chip with the number of tags left ( 3 )
1

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>

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.