DEV Community

Muhammad Awais
Muhammad Awais

Posted on

13 2

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay