Link to code: https://codesandbox.io/s/objective-darwin-w0i5pk?file=/src/App.js
Description: There are four gray squares in this example, each with a different shade of gray. The goal is to change the background color of each square when the user hovers over them, increasing the RGB value by 10.
Issue: The problem arises when moving the mouse from one square to another; the initial square does not revert back to its original color state.
Help Needed: Could someone clarify why this is happening and provide guidance on how to resolve it as I'm unsure of the solution?
Note: I am attempting to achieve this without using CSS for hover effects, instead specifying the backgroundColor through JavaScript
import React, { useState } from "react";
import "./styles.css";
const tabs = [
{ name: "1", img: [] },
{ name: "2", img: [] },
{ name: "3", img: [] },
{ name: "4", img: [] }
];
const initialState = {};
tabs.forEach((t, i) => {
initialState[i] = false;
});
export default function App() {
const [hover, setHover] = useState(initialState);
return (
<div className="App">
{tabs.map((t, i) => {
const v = 50 - (i + 1) * 10;
const val = hover[i] ? v + 10 : v;
return (
<div
key={t.name}
className="tab"
onMouseOver={() => {
setHover({
...hover,
[i]: true
});
}}
onMouseLeave={() => {
setHover({
...hover,
[i]: false
});
}}
onMouseOut={() => {
setHover({
...hover,
[i]: false
});
}}
style={{
backgroundColor: `rgb(${val}, ${val}, ${val})`,
height: "100px",
width: "100px"
}}
>
<p>{t.name}</p>
</div>
);
})}
</div>
);
}
.App {
font-family: sans-serif;
text-align: center;
margin: 0;
padding: 0;
}
* {
margin: 0;
padding: 0;
}
Initial State Image: