React JS - Set State of Parent Component from Child

surjithctly

Surjith S M

Posted on October 26, 2020

React JS - Set State of Parent Component from Child

Parent

function Parent() {
    const [value, setValue] = React.useState("");

    function handleChange(newValue) {
      setValue(newValue);
    }

    // We pass a callback to Child
    return <Child value={value} onChange={handleChange} />;
}
Enter fullscreen mode Exit fullscreen mode

Child

function Child(props) {
    function handleChange(event) {
        // Here, we invoke the callback with the new value
        props.onChange(event.target.value);
    }

    return <input value={props.value} onChange={handleChange} />
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
surjithctly
Surjith S M

Posted on October 26, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related