Careeroza
Child to Parent
Callback Props
Example
A child cannot change parent state directly. The parent passes a function as a prop; the child calls it with data.
import { useState } from 'react';
function SearchBox({ onSearch }) {
const [text, setText] = useState('');
return (
<div>
<input value={text} onChange={(e) => setText(e.target.value)} />
<button onClick={() => onSearch(text)}>Search</button>
</div>
);
}
export default function App() {
const [query, setQuery] = useState('');
return (
<div>
<SearchBox onSearch={setQuery} />
<p>Parent received: <b>{query || '(nothing yet)'}</b></p>
</div>
);
}Result