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

Loading data with limit offset in AngularJS can lead to controller functions crashing and causing data to become jammed

I have developed a video gallery application similar to Youtube using AngularJS. The application includes a REST API which is accessed through Angular services. There are two controller files in the application with similar functionalities but calling diff ...

Utilizing Jquery within Reactjs

Currently, I am encountering an issue while attempting to implement Materialize CSS in React JS. Some of the CSS components require jQuery for initialization or animation. Is it advisable to use jQuery in React JS? And if so, how can I incorporate jQuery ...

Changing the size of various types of images

Is there a way in JavaScript to automatically resize and fill in a block with fixed width using different images with various dimensions? I came across something similar, but it was in AS2. I'm unsure if it can be translated to JavaScript. var _loc3 ...

Tips on changing the outline color by clicking

I'm working on a simple code where I need to change the outline color when a user clicks on a text field. <input type="text" id="box1" /> <input type="password" id="box2" /> <input type="email" id="box3" /> <input type="submit" ...

Tips for displaying ajax search results in Laravel views

My attempt to send a JSON response via AJAX to my Laravel view is not yielding any successful results. public function viewMasakanAjax(Request $request) { if($request->ajax()) { $alberMasakan = Masakan::where('alber_nama_masakan&ap ...

In React TS, the function Window.webkitRequestAnimationFrame is not supported

I'm facing an issue where React TS is throwing an error for window.webkitRequestAnimationFrame and window.mozRequestAnimationFrame, assuming that I meant 'requestAnimationFrame'. Any suggestions on what to replace it with? App.tsx import Re ...

Adjusting the width of input textboxes for alignment

I currently have a set of input textboxes that I have attempted to align using CSS with the {width: xxx px;} property. However, this method is unreliable as it does not consistently ensure proper alignment. <style> #left_col p { margin-top: 15px ...

Tips for aligning a div within a flexbox to the bottom position

I'm having trouble aligning the div at the bottom of the flex box. I attempted to use align-content: flex-end; but it didn't work. Is there a way to keep the <.div class="parameters"> at the bottom of the row? Especially when the ...

Using `useState` within a `while` loop can result in

I'm working on creating a Blackjack game using React. In the game, a bot starts with 2 cards. When the user stands and the bot's card value is less than 17, it should draw an additional card. However, this leads to an infinite loop in my code: ...

What are the steps to modify or remove a node in react-sortable-tree?

I am currently working on implementing a drag and drop tree view using react-sortable-tree. Along with that, I also need to incorporate CRUD operations within the tree view. So far, I have been successful in adding, editing, and deleting nodes within the p ...

When I try to increase the date by 1 day using the MUI X Date picker, it does not update as expected

I have encountered an issue where adding 1 day to my date picker on button press results in it jumping to 01/01/1970. The same occurs when attempting to subtract 1 day from it. My goal is to achieve the following: Refer to this image of my Date picker: D ...

Focus on a specific button based on its text inside

Two buttons are present with the same class but different content <a class="button ordrViewBtn">Sold Out</a> <a class="button ordrViewBtn">Re-Sell</a> I want to change the color of the "Sold Out" button. Is it p ...

Having trouble with the post request in Express JS and Vue? Don't worry, we've got you covered

I've been following a tutorial to set up a basic app and everything is working smoothly, except for the post request which seems to be causing me trouble. Tutorial: https://www.youtube.com/watch?v=HkIGAqAP1GY Although the issue is reproducible based ...

"Instead of seeing the expected content, a blank page is showing

I've been searching for a solution to this problem without any luck. Any assistance would be greatly appreciated. Initially, I created a "tabs" default project which worked fine as a base. However, after making a few modifications, the screen ended u ...

Reduce the dimensions of a CSS attribute automatically

Displayed below is the image with a width of 192 and height of 109: <a href="https://www.blogger.com/u/1/blogger.g?blogID=4402911157743442948#"><img alt="" class="thumbnail" height="109" src="https://2.bp.blogspot.com/-E5ftfbCCgkw/XjnLpO347cI/AAA ...

The map function appears to be malfunctioning or there may be an issue with the retrieved data

Encountering an error message that says "Cannot read properties of undefined (reading 'map')" while attempting to render a list. Below is the code snippet, seeking assistance. import React, { Component } from 'react' // import axios fro ...

Efficiently perform complex nested grouping using the powerful array

Hi, I'm currently facing difficulties while attempting to utilize the array.reduce() function in order to achieve correct grouping for a specific scenario: Here is my original array: { { descriptionFunction: "Change", processDate: "201 ...

Encountering a TypeError in NextJs apps when using next-i18next: NextI18Next seems to be unrecognized as

I am currently in the process of creating a multi-language website using next.JS and the next-i18next package. I have transitioned my project from i18next to next-i18next. The server is up and running at http://localhost:3000 I am encountering an error t ...

What is the best way to implement an onHover event in material-table?

Currently, I am experimenting with the library material-table and my goal is to add a highlighting effect to the row that I am hovering over. Even after referring to the official documentation, I could only find an example showcasing a color change on cli ...

Unfortunately, I am unable to utilize WebStorm in combination with React

Struggling to set up a React project in WebStorm, it's not running and ESLint isn't recognizing it. Started a new React project with Node.js v16: Successfully created the React project: Encountering issues as ESLint is not recognizing the ...