Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

331
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda