Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

340
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda