- parent component passes an object to a child component:
{
width: 20,
isEnabled: true
}
- child component edits object
- changes reflected in parent component
- parent
- pass update function to child
const UpdateItem = (name, val) => { setItem((prevState) => ({ ...prevState, [name]: val, })); } <Child item={item} updateItem={UpdateItem} />
- child
- changing state via
setItem
is asynchronous - must use
useEffect
which is called after state has changed - in
useEffect
, call parent update function
useEffect(() => { props.updateItem("width", item.width); }, [item.width]);
- changing state via
-
handling a checkbox requires using the
checked
propertyconst OnChangeChecked = (e) => { const { name, checked } = e.target; setItem((prevState) => ({ ...prevState, [name]: checked, }));
- convert to Typescript
- test with other input types
- radio button group
select aka dropdown list
- nodejs
$ git clone https://github.com/TrevorDArcyEvans/parent-child
$ cd parent-child
$ npm install
$ npm start