DEV Community

Muhammad Awais
Muhammad Awais

Posted on

Passing props from child to parent react

How to get an updated state of child component in the parent component using the callback method?

let's take an example that you have two components Form and input-box having a parent-child relationship.

Form (Parent)

import React, { useState, Component } from 'react';
import Input from '../../shared/input-box/InputBox'

const Form = function (props) {

    const [value, setValue] = useState('');

    const onchange = (data) => {
        setValue(data)
        console.log("Form>", data);
    }

    return (
        <div>
            <Input data={value} onchange={(e) => { onchange(e) }}/>
        </div>
    );
}
export default Form;
Enter fullscreen mode Exit fullscreen mode

Input Box (Child)

import React from 'react';

const Input = function (props) {
    console.log("Props in Input :", props);

    const handleChange = event => {
        props.onchange(event.target.value);
    }

    return (
        <div>
            <input placeholder="name"
                id="name"
                onChange= {handleChange}
            />
        </div>
    );
}
export default Input;
Enter fullscreen mode Exit fullscreen mode

above code, snippets help you get the updated value of the input box in parent component named Form on every onChange activity of child component named inputBox.

Top comments (0)