Home > Software engineering >  Add conditional filter in JSX
Add conditional filter in JSX

Time:06-09

What is the best way to add optional filters based on a condition? For instance, consider the following code fragment:

<Menu>
  {itemGroupLevels.map(group) = [
    this.props.itemTypes
      .filter((x) => x.group_level === group)
      .filter((x) => x.article_type_code !== "GRAL")
      {Permission.TEACHER?filter((x) => !x.article_type_code.includes('BACKPACK','LUNCH')):null}
      .map((value) => (

      ])}
</Menu>

How can I add the last filter depending on a condition such as if the user has specific permission to avoid including BACKPACK and LUNCH just if the user is a teacher:

{Permission.TEACHER?filter((x) => !x.article_type_code.includes('BACKPACK','LUNCH')):null}

Otherwise, I do not need to add the filter and just leave the two previous filters.

Thanks for your help

CodePudding user response:

Add an if condition within the filter... this ensures that if the user does not have the proper permissions the filter will not return any values.

<Menu>
  {itemGroupLevels.map(group) = [
    this.props.itemTypes
      .filter((x) => x.group_level === group)
      .filter((x) => x.article_type_code !== "GRAL")
      .filter((x) => {
       if (!Permission.TEACHER) return true
       return !x.article_type_code.includes('BACKPACK','LUNCH')
       })
      .map((value) => (

      ])}
</Menu>

CodePudding user response:

Instead of stacking separate filter() calls, it would be better to move the business logic out into a separate function and filter once. This also means you'll avoid looping over the data multiple times for filtering.

const filterGroupItemTypes = (group, item) => {
  return (
    item.group_level === group &&
    item.article_type_code !== "GRAL" &&
    // TODO: Implement  
    (Permission.TEACHER ? ... : true)
  );
};

And then in your renderer

this.props.itemTypes.filter((item) => filterGroupItemTypes(group, item)).map(...)
  • Related