Skip to content

TrevorDArcyEvans/parent-child

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Parent-child Components in React

screenshot

Problem

  • parent component passes an object to a child component:
{ 
    width: 20, 
    isEnabled: true
}
  • child component edits object
  • changes reflected in parent component

Solution

  • 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]);

Discussion

  • handling a checkbox requires using the checked property

    const OnChangeChecked = (e) => {
      const { name, checked } = e.target;
      setItem((prevState) => ({
        ...prevState,
        [name]: checked,
      }));

Further work

  • convert to Typescript
  • test with other input types
    • radio button group
    • select aka dropdown list

Prerequisites

  • nodejs

Getting started

$ git clone https://github.com/TrevorDArcyEvans/parent-child
$ cd parent-child
$ npm install
$ npm start