简体   繁体   中英

Check if my React array contains value if yes return certain component

I have to render different components based on:

  • if the items contain a certain value
  • and if all 10 items have that value
const MyComponent = ({ data }: Props) => {
  const filteredItems = data.items?.filter(
    (item) => item?.type.includes(MyType.Value1) || item?.type.includes(MyType.Value2)
  );

  filteredItems.map((item) => {
    if (item.type.includes(MyType.Value1)) {
      return (
        <div>
          <Component one />
        </div>
      );
    }
    return (
      <div>
        <Component two />
      </div>
    );
  });
  return null;
};

export default MyComponent;

1/ if the items contain a certain value

(data?.items || []).find(item => [your condition here]) && <ComponentToRenderIfTrue />

2/ if all 10 items have that value

(data?.items || []).every(item => [your condition here]) && <ComponentToRenderIfTrue />

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