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;
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;
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)