Home > Enterprise >  Combining multiple maps in React
Combining multiple maps in React

Time:12-16

Hey I have the current standard component which maps over a list.

  return (
    <div className={classNames("vertical-list-rows", className)}>
      {list.listItemCollection.map((item, index) => (
        <StandardComponnet
          key={`${item.key}-${index}`}
          list={list}
          item={item}
        />
      ))}
    </div>
  );

I'm wondering though is it possible to perform another map - if a condition is true - to "add" an additional map to this logic:

const getFilteredList = (list: ListModel, references: Array<number>) => {
  const filteredList = list.clone();

  filteredList.listItemCollection = new ListItemCollection();
  filteredList.listItemCollection.collection = list.listItemCollection.filter(
    (listitem) => references.includes(listitem.id)
  );

  return filteredList;
};


  return (
    <div className={classNames("vertical-list-rows", className)}>
      {list.grouping.groups.map((group) => {
        const filteredList = getFilteredList(list, group.reference);
        <StandardComponnet
          key={`${item.key}-${index}`}
          list={list}
          item={item}
        />;
      })}
    </div>
  );

So the first snippet is the component's standard behaviour, but if a condition is true, I'd like to map over the second snippet as well - is this possible?

CodePudding user response:

Use the ternary operator, and either return an array map or null.

function List() {
  const arr = ['a', 'b', 'c']
  return (
    <div>
      {
        arr.map(val => {
          return (
            <div>
              {val}
              {
                val==='a' ? [1,2,3].map(num => {
                  return <div>{num}</div>
                })
                : null
              }
            </div>
          )
        }
      }
    </div>
  )
}

CodePudding user response:

For me, I often use this style of code:

<View>
{[
  ...list1,
  ...(<condition> ? list2 : []),
  ...(<condition> ? list3 : []),
].map(item => (
  /* render what you need */
))}
</View>
  • Related