Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

329
Views
Add and remove FROM favorites functionality in REACT

I am working on a simple Reactjs app where I have come across a problem. Currently I am having an add to favourite functionality which is working as follows:

In App.js:

function handleAddFavourite(name){
const newFav = Object.values(Data).find(e => e.name === name)
if(favourites.find((n)=>n.name === name)){
  const newFavList = favourites.filter((n)=>n.name!==name)
  setFavourites(newFavList)
}
else {
const newFavList = [...favourites,newFav];
setFavourites(newFavList)
}

}

Here I am passing handleAddFavourite and favourites in context to a nested child(SingleData).

The structure of my react app can be seen as App.js(sends data to datafetched)-> DataFetched(receives data from data fetched and passes to singledata that is basically a row for every single data in data) -> singledata

In my singledata component I show data in multiple rows with an add to favourite button which on being clicked successfully adds the required data to favourites.

singledata.js:

const {handleAddFavourite} = useContext(DataContext)

const styleProp = (favourites.find((n)=>n.name === name))? "gold" : "white"

<td>
    {last}
</td>
<td>
<i class ="fa fa-star" style={{color:styleProp}}  onClick={()=>handleAddFavourite(name)} />
 </td>

Now what I am wanting to do with my add to fav func is that whenever a star icon is clicked the data is added to favorites(already working) and the color of star to change to gold. For this my idea was to get the complete list of fav in singledata component and check if data in fav then change style color of star but the problem here is that the favourites list is being rendered many times for every row of data which i think is a bad practice.And I cant find a way to solve this.

Also the same goes for removing from favourite where the star color changes back to white and data is removed from favourites

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!