Home > Blockchain >  Change state of parent component in child component
Change state of parent component in child component

Time:02-10

I want to change a value in the parent component by changing the state in the child component which is passed by props.

// This is the parent component
const [showEdit, setShowEdit] = useState(false);
<EditApplicationSettings
  appSettings={appSettings}
  changeState={(showEdit) => setShowEdit(showEdit)}
/>

// This is the child component
export default function EditApplicationSettings({ appSettings, props }) {
  return (
    <button
      className="button-red"
      onClick={() => props.changeState(false)}
    >
      Cancel
    </button>
  );
}

When I click on the button, that should change the state in parent, but instead, I get an error.

TypeError: Cannot read properties of undefined (reading 'changeState')

Where did I do wrong in passing the props?

CodePudding user response:

In React terms props tends to refer to the entire property object:

EditApplicationSettings(props)

But since you're destructuring the properties from the object you need to reference the changeState property explicitly:

EditApplicationSettings({ appSettings, changeState })

and

onClick={() => changeState(false)}

CodePudding user response:

To solve this error

TypeError: Cannot read properties of undefined (reading 'changeState')

then this line

export default function EditApplicationSettings({ appSettings, props }) {

should be

export default function EditApplicationSettings({ appSettings, ...props }) {
                                                               ^^^

You could read more at MDN doc for destructuring assignment

  • Related