Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change state of parent component in child component

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading