Skip to content
Advertisement

reactjs setstate not working in function that has .map

Good Morning.

Need help, i have the below script, the thing is the setState is not working, I think I’m missing something here? or Am i doing wrong. the “return” in the below is inside “.map” so i could display the 3 file in the array. Thanks

JavaScript

Advertisement

Answer

I imagine you want to recreate the file array, just changing the activateButton property of the clicked item to true. To do this in React, you must clone the array, mapping all items to themselves, except the one that you clicked. This one you create from scratch, spreading all the old properties and setting activateButton to true. Here’s the code:

JavaScript

Comments:

activatebutton = (file) => (event) => {

We want activatebutton to be a second order function, which receives the clicked item and then the event. Even better would be to pass only the id directly.

this.setState((state) => { … })

Whenever you want to update the state based on itself, use the functional setState. Pass a function whose parameter is the current state and the return is an update object. In this case, the file property of state.

item.id === id ? { …item, activateButton: true } : item

This is short for:

JavaScript

I made a CodeSandbox Demo which even includes as the doubleClick event the toggling of the item.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement