Here's an uncomplicated solution:
.App {
display: flex;
}
.box {
width: 150px;
height: 150px;
margin: 20px;
padding: 20px;
}
import React from "react";
import "./styles.css";
export default function App() {
const [bg, changeBGColor] = React.useState(1);
return (
<div className="App">
<div
className="box"
onClick={() => changeBGColor(1)}
style={{
backgroundColor: bg === 1 ? "black" : "red"
}}
/>
<div
className="box"
onClick={() => changeBGColor(2)}
style={{
backgroundColor: bg === 2 ? "black" : "yellow"
}}
/>
<div
className="box"
onClick={() => changeBGColor(3)}
style={{
backgroundColor: bg === 3 ? "black" : "green"
}}
/>
</div>
);
}
Copy and paste this code into Codesandbox to view the result.
In this example, I'm utilizing a React hook that takes a unique id as input. If set, the corresponding component will appear in black
.
Therefore, the first div
is initially black
. When I click on the second div
, the value of bg
changes to 2
and in the style
, I check if 2
is selected then set the color to black
. The same process applies to the third div.