score:0

one solution is to make a generic change() function with a parameter for the key that should be changed:

change(key, value) {
   setstate({key: value, ...this.state});
}

now when you want to add a listener to a child component:

<foo onchange={ value => change('foo', value) }/>
<bar onchange={ value => change('bar', value) }/>

score:1

when we see how react works. it is based on one-directional data flow. so, usually the application state is kept at the top most component (say, app component) in your case. so that data/state can be passed down as props to the component that needs it.

there, however may be the cases where children components of the parent, needs to work with the same data(say in case of an event - a button click that happens in the child component.) in that case we write a function in the parent component and pass the function as props to the children, so that the state gets updated in the parent itself and any child gets updated data.

1-way-data flow in react

in pure react (without using any state management library), we have to pass the state as props to work with our app. but in case you choose to use a state management library such as redux, then the components (known as containers) can directly communicate with the application state.

and if your application state contains objects within objects(like you have shown) or array of objects containing more objects, then you cannot use setstate() to update the state directly. in most of the cases, you take copy of the state and then use json.parse(json.stringify(state)) to do deep cloning and work with the state in a best possible manner.

there are other things in the example, the functions that you have used within the class , you need to bind the scope of this variable to point to the current class. this we do inside the constructor method, or simple make use of arrow function in order to avoid errors.

if you need more explanation, i will share with you :)

score:1

when you see that the state of your react application is getting out of hand, it's usually time to bring in a state management library like redux (there're a few and redux is the most popular one).

it'll help you have a global state that is managed in a reasonable way.


Related Query

More Query from same tag