Skip to content
Advertisement

React Controlled Form with Child /Parent component

I’m building a controlled form with dynamic fields. The Parent component get data from a redux store and then set state with the values. I don’t want to make it with too much code lines so I turn the dynamic fields into a component. States stay in the parent component and I use props to pass the handlechange function.

Parent :

JavaScript

Child :

JavaScript

Everything is fine when I’m typing in the Parent inputs. But when I’m using Child fields state update for one character but come back at its previous state right after. It also doesn’t display the character change. I can only see it in the console. Thanks you in advance for your help

Advertisement

Answer

The problem is that you’re mutating the state directly. When you create the articles variable (let articles = press) you don’t actually create a copy and articles doesn’t actually contain the value. It’s only a reference to that value, which points to the object’s location in memory.

So when you update articles[index].title in your handleChangeChild function, you’re actually changing the press state too. You might think that’s fine, but without calling setPress() React will not be aware of the change. So, although the state value is changed, you won’t see it because React won’t re-render it.

You need to create a copy of the press array using .map() and create a copy of the updated array element. You can find the updated handleChangeChild() below:

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