First of all, I am just a beginner learning React so bare with me.
I am trying to display an icon with different color if it fits a condition. I know I have to use useEffect and also the map method. But I don't get to develop it the right way. This is what I have:
export const PreloadCard = ({ preload }) => {
const { favorites } = useSelector( state => state.favorites );
const favoriteIconColor = useEffect(() => {
favorites.map( favorite => {
if ( favorite.preloadID.includes(preload.preloadID) )
return () => {
"error"
}
})
}, [favorites])
return (
<List>
<Card>
<CardHeader
action={
<IconButton aria-label="add to favorites">
<FavoriteIcon color= { favoriteIconColor }/>
</IconButton>
}
titleTypographyProps={{ variant:'h7' }}
title={ preload.name }
subheader={ preload.artist }
/>
)}
What am I doing wrong? Thank you!
CodePudding user response:
I don't quite understand your expected behaviour but I'll assume 'error' is a colour
You don't need useEffect
if anything you should use useMemo
-
const favoriteIconColor = useMemo(() =>
favorites.some(favorite => favorite.preloadID.includes(preload.preloadID)) ? 'error' : undefined
, [favorites, preload])
Will give you a colour of 'error' if preloadID matches, else undefined. Feel free to amend as necessary
p.s. apologies for poor formatting, I'm on my phone
CodePudding user response:
Instead of using useEffect you should calculate color before the return statement. Read more about useEffect at https://reactjs.org/docs/hooks-effect.html
export const PreloadCard = ({ preload }) => {
const { favorites } = useSelector((state) => state.favorites);
let favoriteIconColor = '';
favorites.every((favorite) => {
if (favorite.preloadID.includes(preload.preloadID)) {
favoriteIconColor = 'error';
return false;
}
return true;
});
return (
<List>
<Card>
<CardHeader
action={
<IconButton aria-label="add to favorites">
<FavoriteIcon color={favoriteIconColor} />
</IconButton>
}
titleTypographyProps={{ variant: 'h7' }}
title={preload.name}
subheader={preload.artist}
/>
</Card>
</List>
);
};