JS3
JS3

Reputation: 1849

How can I show the button only when the mouse hovers on the color?

I wanted to show the button once you hover on the specific color. However, what happens is, hovering on one color will also show the button for other colors of the same products. Also, the button is on the left side part, so if I'll hover to go to the left side, the button won't appear anymore. This is what happens:

[![enter image description here][1]][1]

Upvotes: 0

Views: 80

Answers (2)

Simon Leroux
Simon Leroux

Reputation: 477

You can use the :hover css selector if you want something simple.

  1. Add a class to your element in you js file

    <div className="color-choice" key={i}>
    
  2. Use the :hover selector in the css file

    .color-choice:hover button { display: block; }

    .color-choice button { display: none; }

Upvotes: 1

Chakib Salah
Chakib Salah

Reputation: 546

You will need to play with elements indexes.

instead of display, we will need to get the indexes of the hovered element:

const [displayIndex, setDisplayIndex] = useState({
  typeIndex: -1,
  colorIndex: -1
});

and the event functions might look like :

  const showButton = (typeIndex, colorIndex) => {
   // e.preventDefault();
   setDisplayIndex({
     typeIndex,
     colorIndex
   });
  };

 const hideButton = () => {
   // e.preventDefault();
   setDisplayIndex({
    typeIndex: -1,
     colorIndex: -1
   });
 }; 

and the will to return the button element checking the displayIndex

 {
   displayIndex.typeIndex === index 
   &&
   displayIndex.colorIndex === i 
   &&
   (<Button ....>Add</Button>
 }

Made this modification on your sandbox link https://codesandbox.io/s/add-to-cart-sampled-2-forked-9oi1kn?file=/src/App.js , you might need to fix some styling there.

Hope you find this useful .

Upvotes: 0

Related Questions