skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. You can achieve this like that

    const backgroundColors = [{color: "#FDFFB6"}, {color: "#FFD6A5"}, {color: "#FFADAD"}, {color: "#CAFFBF"}];
    export default function App() {
        const [currentColor, setCurrentColor] = useState('#FDFFB6')
    
        const setColor = (color) => {
            setCurrentColor(color);
        }
    
    
        return (
            <RootStyle>
                <Stack sx={{backgroundColor: currentColor}} width={100} height={100}/>
                <Stack width={120} gap='20px'>
                    {backgroundColors.map(item =>
                        <button
                            key={item.color}
                            style={{ background: item.color }}
                            onClick={() => setColor(item.color)}
                        >{item.color}</button>
                    )}
                </Stack>
            </RootStyle>
        );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search