Search code examples
javascriptreactjshoverdestructuringonmouseover

Change styles on hover of an appropriate item


How can I Change styles on hover of an appropriate item react? Now the styles are changed of all of the items at a time. Hovering on add to cart button I need to change only the chosen div styles. https://codesandbox.io/s/trusting-moon-djocul?file=/src/components/Category.js**

import React, { useState } from "react";

import styles from "./category.module.css";
import Categories from "./Categories";

const Category = () => {
  const [hovered, setHovered] = useState(false);
  const [data, setData] = useState(Categories);

  const style = hovered
    ? { backgroundColor: "#ffcbcb", color: "#fff", transition: "all 0.5s ease" }
    : {};
  const filterResult = (catItem) => {
    const result = Categories.filter((curData) => curData.category === catItem);

    setData(result);
  };

  return (
    <>
        <div className={styles.items}>
          {data.map((value) => {
            const { id, title, price, description } = value;
            return (
              <>
                <div className={styles.item} key={id} style={style}>
                  <h1>{title}</h1>
                  <p>
                    {price} <span>$</span>
                  </p>
                  <p>{description}</p>
                  <button
                    onMouseEnter={() => setHovered(true)}
                    onMouseLeave={() => setHovered(false)}
                    className={styles.btn}
                  >
                    Add to Cart
                  </button>
                </div>
              </>
          
  );
};

export default Category;


Solution

  • That's because you have a single "hovered" state shared between all your cards, you should create a "Card" component and have that component have its own hovered state

      return (
        <>
            <div className={styles.items}>
              {data.map((value) => {
                return (
                  <>
                   <Card {...props} />
                  </>
              
      );