below I have a series of React code that has several circles displayed on a page, each with a different color. When a color is clicked, the nav
displays that change by reading off the selected color.
import { useState } from "react";
const Color = ({ color, setSelectedColor}) => {
return <div className={color} onClick={() => setSelectedColor(color)}></div>;
};
const App = () => {
const [selectedColor, setSelectedColor] = useState("");
return (
<div id="container">
<div id="navbar">
<div>Currently selected: </div>
<div className={selectedColor}>{selectedColor}</div>
</div>
<div id="colors-list">
<Color color="violet" setSelectedColor={setSelectedColor}/>
<Color color="orange" setSelectedColor={setSelectedColor}/>
<Color color="yellow" setSelectedColor={setSelectedColor}/>
</div>
</div>
);
};
export default App;
I don’t think you all need any other code, but if you do need it let me know!
There is a class
in CSS that I have called selected
which just creates a border around a circle. The problem I am having is how exactly do I apply the class
to the selectedColor
? I am thinking of ternary operators, but I am a tad bit new to React, so I am unsure how I should implement this.
Any help is greatly appreciated!
2
Answers
You need to add a variable to check if the
color
prop matches theselectedColor
, and if they match you add theselected
class, and with the ternary operator you can apply both thecolor
andselected
classes.You can enhance the Color component by adding an "isSelected" attribute. This attribute will indicate whether the current color matches the selected color. Consequently, based on the value of the "isSelected" attribute, you can dynamically apply the "selected" class alongside the "color" class on the Color component.
here is the modified code: