0

I am trying to map out data into a react component, but I only want unique instead of duplicate components to render to the page. I was researching on how to use the filter, Set, and unique methods was having a hard time figuring out how to work a React component into the syntax

so far....

import React, { useContext } from 'react'
import Tag from '../components/Tag'
import feedbackContext from '../utils/FeedbackContext'

const Tags = () =>{

    const data = useContext(feedbackContext)
    

    return(
        <>
        {
            data.map((tag,id) =>(
                <Tag key ={id} category={tag.category}/>
            ))
        }
        </>
    )
}

export default Tags

In the code snippet above it renders all tags from the json file which results to duplicates components being rendered. I was looking up the unique, filter and Set methods, but couldn't quite grasp how to use this in the case of rendering unique components. Has Anyone ever done this before?

Update, let me rephrase what I meant from above, it the snippet below, I simply want just one of each category name appearing. It's technically not duplicating:

<div class="filter">
<div class="category_type">enhancement</div>
<div class="category_type">feature</div>
<div class="category_type">feature</div>
<div class="category_type">enhancement</div>
<div class="category_type">feature</div>
<div class="category_type">bug</div>
<div class="category_type">feature</div>
<div class="category_type">feature</div>
<div class="category_type">feature</div>
<div class="category_type">feature</div>
<div class="category_type">bug</div>
<div class="category_type">enhancement</div>
</div>
Stitch
  • 203
  • 3
  • 16
  • can you show example of data duplicates? – Viet Jul 12 '21 at 03:08
  • I mean the array `data` – Viet Jul 12 '21 at 03:15
  • So technically its not duplicated, but I just want just one of each category name appearing – Stitch Jul 12 '21 at 03:18
  • Use this `[...new Set(data.map(({category}) => category))]` – Hassan Imam Jul 12 '21 at 03:51
  • How to get a list of unique values from an array https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates – Matthew Kwong Jul 12 '21 at 03:53
  • @HassanImam, that didn't quite work when I added in the full component syntax, but it did work by destructing the object as expected, I was doing this in a sandbox earlier today. I may just modify it in that my coding using that and style it from there. – Stitch Jul 12 '21 at 03:59
  • 1
    Give it a try, this will get you distinct category and then you can map this array. – Hassan Imam Jul 12 '21 at 04:08

0 Answers0