Trying to target each image on hover not all at once

Viewed 36

I'm trying to hover over each image and have different content(an image or text for this example) show for each image.

Right now when I hover over a image it changes to all of them. I know i have to use an event but not sure on how to use it using hooks.

const Logos = () => {
const [defaultImg, setNewImg] = useState("image1");

const onMouseLeave = (e) => {
console.log(e.target, "img leave");

setNewImg("image1");
};

const onMouseEnter = (e) => {
console.log(e.target, "enter");

setNewImg("image2");
};

return (
<div className="images">
  <div className="logos-container">
    <h3 className="title">Trinity title goes here</h3>
    <div className="logos">
      {logos.map((logo) => (
        <Link to="/">
          <img
            key={logo.image}
            src={defaultImg}
            alt=""
            className="logo"
            onMouseLeave={onMouseLeave}
            onMouseEnter={onMouseEnter}
          />
        </Link>
      ))}
    </div>
  </div>
</div>
);
};
1 Answers

You are changing the state for every images since you pass the same defaultImg to each image.

You should probably put this logic in an Image component that handles its own state.

const Image = ({ logo }) => {
  const [defaultImg, setImg] = useState(BreezeLogo);

  const onMouseLeave = (e) => {
    console.log(e.target, "img leave");

    setImg(BreezeLogo);
  };

  const onMouseEnter = (e) => {
    console.log(e.target, "enter");

    setImg(SafebridgeLogo);
  };

  return (
    <img
      key={logo.image}
      src={defaultImg}
      alt=""
      className="logo"
      onMouseLeave={onMouseLeave}
      onMouseEnter={onMouseEnter}
    />
  );
};

const Logos = ({ logos }) => {
  return (
    <div className="images">
      <div className="logos-container">
        <h3 className="title">Trinity title goes here</h3>
        <div className="logos">
          {logos.map((logo) => (
            <Link to="/">
              <Image logo={logo} />
            </Link>
          ))}
        </div>
      </div>
    </div>
  );
};

Related