Tips to use useEffect to maintain background color state
P粉131455722
2023-08-18 15:08:53
<p>I'm trying to save the background color of the wishlist toggle button so that when the user moves across pages, the color of the button remains "black" to show the user that they have saved the item to the wishlist. </p>
<pre class="brush:php;toolbar:false;">const Item = (props) => {
const dispatch = useDispatch();
const [background, setBackground] = useState(false);
function addToCartHandler(product) {
dispatch(addToCart(product));
}
function toggleWishlistHandler(product) {
dispatch(toggleItem(product));
setBackground((current) => !current);
}
return (
<div>
<li className={classes.item}>
<img src={props.img} alt="Item" className={classes.image} />
<div className={classes.description}>
<p className={classes.title}>{props.title}</p>
<p className={classes.price}>£{props.price}.00</p>
</div>
<div className={classes.actions}>
<div
className={`${classes.addWishlist} ${classes.icon}`}
onClick={() => toggleWishlistHandler(props.product)}
style={{
backgroundColor: background ? "black" : "orange",
}}
>
<i className="fa-solid fa-heart"></i>
</div>
<div
className={`${classes.addCart} ${classes.icon}`}
onClick={() => addToCartHandler(props.product)}
>
<i className="fa-solid fa-bag-shopping"></i>
</div>
</div>
</li>
</div>
);
};
export default Item;</pre>
You can save colors in local storage.