The Dead Man
The Dead Man

Reputation: 5576

React, onMouseEnter event trigger all items instead of one hovered?

I have two cards now when I hover on one card it triggers in all two cards on hover (onMouseEnter) Here is the solutions I have

import React, { useState } from "react";

const Buttons = () => {

  const [isShown, setIsShown] = useState(false);

  return (
    <div>
      <div
        onMouseEnter={() => setIsShown(true)}
        onMouseLeave={() => setIsShown(false)}
        className="wrapper-btn"
      >
        {isShown && <button> test 1 </button>}
      </div>
      <div
        onMouseEnter={() => setIsShown(true)}
        onMouseLeave={() => setIsShown(false)}
        className="wrapper-btn"
      >
        {isShown && <button> test 2 </button>}
      </div>
    </div>
  );
};

export default Buttons;

What is wrong here?

Upvotes: 0

Views: 564

Answers (1)

buzatto
buzatto

Reputation: 10382

both share the same state, you can abstract your code to another component where each one has an independent state:

import React, { useState } from "react";

const Buttons = () => {
  return (
    <div>
      <ButtonDisplay btnContent='test 1' />
      <ButtonDisplay btnContent='test 2' />
    </div>
  );
};

export default Buttons;

const ButtonDisplay = ({ btnContent }) => {
  const [isShown, setIsShown] = useState(false);

  return (
    <div
      onMouseEnter={() => setIsShown(true)}
      onMouseLeave={() => setIsShown(false)}
      className="wrapper-btn"
    >
      {isShown && <button> { btnContent } </button>}
    </div>
)}

this would be the approach I would take since keeps your code dry.

other approach possible would change isShown state to an array that tracks each button isShown state, where onMouseEnter|Leave would update a specific index of that array and also read from that one, hence you would render your button based on specific value from an index of your state. or you could create a state to each button which would be the least optimal when you have multiple buttons.

Upvotes: 1

Related Questions