Skip to content
Advertisement

React JS – Change parent state on child click, map not iterable

I am new to React and dev in general, but I am struggling to figure out how to achieve what I am trying to do. I feel as though I may have missed something along the way.

My goal is to have a list of items, that which on clicked individually, will toggle the visibility of their information.

The problem is that I am not able to map over the state in the parent element to display each object. But the state is in an array so I don’t understand why it wouldn’t be iterable. I do not get this problem when its just an object that I pass props to the child without state.

Is this the correct way to go about doing this? Am I supposed to create another array just to map over my object? I’ve also been a little confused as some sources create a class and use the constructor and render function. Is that deprecated or should I be doing it this way?

Parent

JavaScript

Child

JavaScript

Advertisement

Answer

There are a number of problems with your code.

The first has been pointed out by @talfreds in their answer – you need to call useState() to initialize the state variable and its corresponding setter.

JavaScript

Just doing this should allow your component to render.

But once you click the button, your current toggle handler will overwrite the array stored in habits with a boolean.

To fix this you need to understand that the callback you pass to setState is passed the current value of the relevant state variable for you to work with, and the state will be set to the value that you return from the callback. When working with arrays you need to avoid directly mutating this passed value, in this example by using map() which returns a new array, and by cloning the ‘habit’ object that we are changing use spread syntax.

JavaScript

The last glaring problem is your use of this which is necessary when working with a class based component, but isn’t necessary in a function component and actually won’t work at all in the context of an arrow function.

Here is a shortened example snippet that may help you working through these ideas.

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