0

The user has own list of tags and each item owned by the user can have multiple tags from this tag list.

Here I am trying to map all the users tags for one item and if the specific item has a tag from the userTag list then those tag Chip element should have a different style aqua coloured background.

I am struggling on finding a way to get the 'tag: array' values and implementing the Chip element style accordingly to multiple tags. Here I can only get the item.tag array for the first tag item.tag[0]. How would I go by when trying to get each value from the nested tag array inside itemsData and give the item multiple aqua coloured tags if it has multiple tags.

 example

 const itemsData = [
 { id: 1, tag: ['Fysik', 'Matematik'] },
 { id: 2, tag: ['Analytics', 'Marketing', 'Data'] },
 { id: 3, tag: [''] },
 ];
<div>
  {userTags.map(tag => (
    <Chip
      label={tag}
      variant={item.tag[0] === tag ? 'default' : 'outlined'}
      onClick={() => { onTagSelected(tag, item.id); }}
    />
  ))}
</div>
0

3 Answers 3

1

You could use Array.indexOf to determine whether it is in the item's tag array or not.

<div>
  {userTags.map(tag => (
    <Chip
      label={tag}
      variant={item.tag.indexOf(tag) > -1 ? 'default' : 'outlined'}
      onClick={() => { onTagSelected(tag, item.id); }}
    />
  ))}
</div>
Sign up to request clarification or add additional context in comments.

Comments

1

You could check if some of the items tags includes the tag:

 itemsData.some(item => item.tag.includes(tag))

If you do that check more often on a large dataset it might be benefitial to build up a Set, then lookup is O(1):

 // Build up the Set once
 const highlightedTags = new Set(itemsData.flatMap(item => item.tag));

 // Then lookup:
 highlightedTags.has(tag)

1 Comment

Set seems overkill since the number of tags for an item wouldn't be a large dataset.
0

Try this:

 <div>
      {userTags.map(tag => (
        <Chip
          label={tag}
          variant={item.tag.includes(tag) ? 'default' : 'outlined'}
          onClick={() => { onTagSelected(tag, item.id); }}
        />
      ))}
    </div>

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.