Categories
React Answers

How to change child component’s state from parent component with React?

Spread the love

Sometimes, we want to change child component’s state from parent component with React.

In this article, we’ll look at how to change child component’s state from parent component with React.

How to change child component’s state from parent component with React?

To change child component’s state from parent component with React, we can pass props.

For instance, we write

const Child = ({ open }) => {
  return <Drawer open={open} />;
};

const ParentComponent = () => {
  const [isOpen, setIsOpen] = useState(false);

  const toggleChildMenu = () => {
    setIsOpen((prevValue) => !prevValue);
  };

  return (
    <div>
      <button onClick={toggleChildMenu}>Toggle Menu from Parent</button>
      <Child open={isOpen} />
    </div>
  );
};

to set the open prop of the Child component to the isOpen state’s value in ParentComponent.

Then in child we pass the open prop as the value of the open prop of the Drawer.

Conclusion

To change child component’s state from parent component with React, we can pass props.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *