Using React I’m building a simple application for sticky notes where you can add as many sticky notes as you want.
I’m trying to add functionality to change the colour of the sticky note but it changes it for every sticky note present.
What can I do to my code below so that when I click the button, it only updates the sticky note in which I’m selecting the colour from?
I’m using state to update the colour but every sticky notes is affected by this.
I currently have a drop down menu from the sticky note that displays buttons (colours) I can select from.
const backgroundColors = [
{
color: "#FDFFB6",
},
{
color: "#FFD6A5",
},
{
color: "#FFADAD",
},
{
color: "#CAFFBF",
}
];
const [currentColor, setCurrentColor] = useState('#FDFFB6')
const setColor = (color) => {
setCurrentColor(color);
}
{backgroundColors.map((color, index) => (
<button
className="w-4 h-4 rounded-full mx-1"
style={{ background: color.color }}
onClick={() => setColor(color.color)}
>
2
Answers
That’s not really enough code to be very explicit in how to address your use case, but generally you need to associate the color state with the individual instance of a "StickyNote" react component.
You can do this by making sure the markup and state associated with notes is it’s own component, and then implementing the button with the color-picker inside that note component. If modifying the
currentColor
is applied to all notes that suggests you are rending all notes with the same state / within a single react component.You can achieve this like that