0

I have an application in react js, there is a list of elements and when the user hover over the element the background color should change to red. At the moment it works. Also i want when i leave the element unhover, the element should be without red background, but now when i leave the element the color does not dissappear. Basically the hover should affect only that element where the user hover.

import "./styles.css";
import React, { memo, useEffect, useState } from "react";

const Element = ({ id }) => {
  const styles = {
    background: "red"
  };
  const [isHovered, setIsHovered] = useState(false);

  return (
    <div
      className={isHovered ? "hovered" : ""}
      onMouseOver={() => {
        setIsHovered(true);
      }}
    >
      hello {id}
    </div>
  );
};

export default function App() {
  return (
    <div className="App">
      {[0, 1, 2].map((el) => {
        return <Element key={el} id={el} />;
      })}
    </div>
  );
}

demo: https://codesandbox.io/s/compassionate-einstein-9v1ws?file=/src/App.js:0-557
Question: Who can help to solve the issue?

1 Answer 1

1

Instead of onMouseOver, you can use onMouseEnter and onMouseLeave to apply the styles based on the isHovered state.

Here is your updated code.

import "./styles.css";
import React, { memo, useEffect, useState } from "react";

const Element = ({ id }) => {
  // const styles = {
  //   background: "red"
  // };
  const [isHovered, setIsHovered] = useState(false);
  console.log({ isHovered });
  return (
    <div
      // style={{ backgroundColor: isHovered ? "red" : "transparent" }}
      className={"hovered"}
      // onMouseEnter={() => setIsHovered(true)}
      // onMouseLeave={() => setIsHovered(false)}
    >
      hello {id}
    </div>
  );
};

export default function App() {
  return (
    <div className="App">
      {[0, 1, 2].map((el) => {
        return <Element key={el} id={el} />;
      })}
    </div>
  );
}

You can also do the same thing using the className without using the state variable, with just targeting the hover class. I've used the both in the sandbox.

In case of doing only with className, you can just add a className to the div

className={"hovered"}

then, update the styles of the class in the css file.

.hovered:hover {
    background: red;
 }

Updated sandbox

Sign up to request clarification or add additional context in comments.

1 Comment

This will not work on some use cases. If you are hovering over a nested child element (e.g a dropdown content) and this dropdown content unmounts with the use of a keyboard, for instance, there will be no mouse events triggered, therefore the isHovered state will never update

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.