Reputation: 4192
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?
Upvotes: 0
Views: 7668
Reputation: 1707
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;
}
Upvotes: 1