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