How to send data from child component to parent component in react
Sometimes we need to pass data from a child component to parent component. For example we have a child component. In child component, We created a input box and a button.When we enter text and click on submit button. We trigger a callback function from parent component and send text input as argument and get data in parent component.
import { useState } from "react";
const Child = (props) => {
const [name, setName] = useState();
const clickHandler = (greet) => {
props.greet(name);
};
return (
<>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button onClick={clickHandler}>Click to Perform</button>
</>
);
};
const App = () => {
const greet = (name) => {
alert(`Welcome ${name}`)
};
return (
<>
<div className="App">
<h1>How to pass data from child to parent component</h1>
<Child greet={greet} />
</div>
</>
);
}
export default App
