简体   繁体   中英

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?

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

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM