How can the color of the wishlist icon be modified in Reactjs when the item is available in the database?

Is there a way to change the color of the wishlist icon based on whether the item is in the database? If the item is present, its color should be brown, and if it's not present, the color should be black.

Additionally, I want the ability to toggle between colors. So if an item is already in the database (brown), clicking on the icon should change it to black and remove the item. Clicking again should add the item back to the database, changing the color back to brown.

If this explanation is unclear, feel free to ask! (The value returned from the database is stored in the [itemPresent] hook)


import React, { useState, useCallback, useEffect } from 'react';
import { useParams } from "react-router-dom";
import { connect } from 'react-redux';
import { BsDash, BsPlus } from "react-icons/bs";
import axios from '../../axios-orders';
import Spinner from '../../components/UI/Spinner/Spinner'
import { RiHeart3Fill } from 'react-icons/ri';

const Details = (props) => {
    
    const { id } = useParams();

    const [toggleHeart, setToggleHeart] = useState(false);
    const [itemPresent, setItemPresent] = useState('');

    useEffect(() => {
        axios.post('/UserPortal/CartItems/get_wishlist.php', {
            customer_id: localStorage.getItem('Id')
        })
        .then((response) => {
          console.log(response.data);
         response.data.map((item) => {
            return setItemPresent(item.product_id)
        })
    
        if(itemPresent === id){
            console.log('[item]',itemPresent)
        }
        });
    },[toggleHeart,id,itemPresent])

    var c = props.orders.find(product => product.id === id);

    const changeColor = useCallback(() => {
        setToggleHeart(!toggleHeart);
        const data = {
            customer_id: localStorage.getItem('Id'),
            name: c.name,
            price: c.price,
            description: c.description,
            quantity: c.quantity,
            product_id : c.id
        };
        axios.post('/UserPortal/CartItems/wishlist.php', data )
            .then((response) => {
              console.log(response.data);
            });
       },[toggleHeart,c.id,c.name,c.price,c.description,c.quantity]);

   if(props.orders.length === 0){
    return <Spinner/>;
   }

 return (
    <div className="details__info">
        {localStorage.getItem('email') 
            ? itemPresent 
                ? <RiHeart3Fill className={
                    toggleHeart ? 'heart active' : 'heart'
                  } onClick={changeColor}/>
                : <RiHeart3Fill className="heart" onClick={changeColor}/>
            : <RiHeart3Fill className="heart"/>
         }
    </div>
 );

CSS FILE

.heart{
    font-size: 35px;
    color:rgb(182, 173, 173);
    margin-top: 7px;
     width: 70px;
     outline: none;
     text-transform: uppercase;
     cursor: pointer;
     font-weight: bold;
     &:hover{
         color: rgb(192, 39, 39);
     }
    &.active {
        color: rgb(192, 39, 39);
    }
}

Answer №1

You have the ability to create CSS classes using the useState hook and can modify them when an item is added or removed.

Check out the code snippet below for a possible solution:

const [cssStyle, setCssStyle] = useState("heart")

useEffect(() => {
  if(toggleHeart) {
    setCssStyle("heart active")
  } else {
    setCssStyle("heart")
  }
}, [toggleHeart])

return (
  <div className="details__info">
  
    {localStorage.getItem('email') ? 
      itemPresent ? 
        <RiHeart3Fill
          className={cssStyle}
          onClick={changeColor}
        />
        : <RiHeart3Fill className="heart" onClick={changeColor}/>
      : <RiHeart3Fill className="heart"/>
    }
    
  </div>
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to automatically adjust the margins of my HTML body page

I'm currently working on a school project to develop a website. The challenge I'm facing is customizing the navbar and header background colors in such a way that they extend seamlessly to the end of the page. Despite my efforts, there seems to b ...

Improving how React deals with routes

Is there a more efficient way to manage react routes for my book store website? I want each book to have its own page with author information and purchase options. Here are my current routes: <Routes> {/* DASHBOARD */} < ...

Having difficulties with JavaScript's if statements

I'm facing an issue with my JavaScript code that is meant to modify the value of a price variable and then display the updated price. The problem arises when I have multiple select options, as the price only reflects the ID of the last statement. Here ...

Is it possible for Penthouse to retrieve critical CSS while using javascript?

I am currently utilizing the laravel-mix-criticalcss npm package to extract the critical CSS of my website. This package leverages Penthouse under the hood, and you can configure Penthouse settings in your webpack.mix.js within the critical options. The ...

What's the best way to determine which of the two forms has been submitted in Django?

On my homepage, I have both a log_in and sign_up form. Initially, the log_in form is displayed by default, but when a user clicks on the Sign Up button, the sign_up form appears. These toggles switch depending on which button the user clicks. from django ...

The route is redirecting to an incorrect destination

Whenever a button is clicked on my webpage, this particular function is triggered. $scope.go=function(takenAt){ var path = '/oneMinuteMetric/loadCapturedMetrics?'+'&timestamp=' + takenAt + '&tagName='+ $stateParam ...

Error: The localStorage object is not defined within the context of a Next.js application

I am developing a Next.js application Here is an example of one of my pages/components: import React from "react"; import { SomeLocalStorageComponent } from "some-external-lib"; const MyComponent = () => { const isBrowser = typeof ...

Looking for a JavaScript snippet to insert the word "Search" into an empty DIV element with the specified id attribute

I am trying to insert the word "Search" into an empty input field with the id "ReportQuery" using JavaScript. Unfortunately, I do not have access to the HTML code directly. How can I achieve this task through coding? Below is the snippet of code that nee ...

Having trouble with $addToSet and $push not working in updates using Mongoose with MongoDB in Node.js?

My issue involves Mongoose as I am attempting to update a document in MongoDB using the mongoose module. Below is my schema: var User = new mongoose.Schema({ name: String, email: String, list_houses: [{ id_house: S ...

Using jQuery's .load() method to load a PHP file can result in an exponential increase in XHR finished loading time with each subsequent load

There seems to be an issue with my code using .load() to load a PHP page into a div whenever the navbar or link is clicked. After multiple clicks, I noticed that the "XHR finished loading" increases exponentially and it appears that the same PHP file is be ...

trouble with phonegap javascript ajax integration

I'm new to app development and I've been trying to create a mobile app using PhoneGap. I have a remote shared server that contains a MySQL table. My goal is to sign up a user, then send the data via JavaScript and AJAX to a PHP server page that w ...

The overall outcome determined by the score in JavaScript

Currently, I am working with a dataset where each person is matched with specific shopping items they have purchased. For instance, Joe bought Apples and Grapes. To gather this information, individuals need to indicate whether they have made a purchase. I ...

In React and TypeScript, when I pass a state as a prop, the data fails to render

Here is the useState function for managing the Data Interestingly, removing this state from the code doesn't affect rendering at all. const [cart, setCart] = useState([] as Product[]); This piece of code handles Mapping and Rendering the Data <Sin ...

What events precede and follow a keydown action in a Textarea field?

I need to prevent users from pressing function keys (F1, F2, etc.), the tab key, and any other characters from being added. The code below is supposed to achieve this on my website but it's not working. document.getElementById("code").addEventList ...

Exploring the capabilities of batch updates in Firestore with the latest web version-9

I am facing issues when trying to update certain values in my firestore collection within my nuxt project. const batch = writeBatch(firestore); const data = query(collection(firestore, `notifications`, `${uid}/news`)); const querySnapshot = await ...

Retrieving HTML Content with Ajax

Currently using this script for an assignment in my class. Still learning! The script checks whether a site is down or not. I want to expand this script to display statuses for each website in the table without duplicating the script. Any suggestions on ...

Experiencing problems with the calling convention in JavaScript

Here is a snapshot of the code provided: If the function testFields at Line:3 returns false, then the program correctly moves to Line:21 and returns the value as false. However, if testFields returns true, the program proceeds to Line:4, but instead of ex ...

Is there a distinction between the values 'normal' and 'stretch' in the CSS property known as 'align-content'?

When it comes to the CSS declaration 'align-content', the default value is 'normal'. But, there is also another option: 'stretch'. I have been having a hard time figuring out if there is any actual difference between the two. ...

Having extra space can occur when adding margin to a div within another div in HTML5

I am facing an issue with the following piece of code: <body> <div class="page-top"> * </div> <div class="page-bottom"> <div class="contentbox"> <h1>CONTENTBOX</h1> </div ...

Removing users from a Socket.IO chat room using Node.js

I am facing an issue with removing users from Socket.IO when their browser is closed. The 'user' in the array 'users[]' is not getting removed or updated. Additionally, I would like to update the users on the client side as well. Can so ...