Sometimes we may need to call a function residing in the parent component from the child component.
In this example, we have a function named capitalizeTitle() which capitalizes the title passed to it.
This function is currently residing in theĀ ParentComponent. We can invoke it using an anonymous function from the child component as follows:
const ParentComponent = () => {
function capitalizeTitle(someTitle) {
alert(someTitle.toUpperCase())
}
return (
<ChildComponent capitalizeTitle={capitalizeTitle} someTitle={'Hello there!'} />
)
}
const ChildComponent = ({ capitalizeTitle, someTitle }) => {
return (
<div>
<h2>{someTitle}</h2>
<button onClick={() => capitalizeTitle(someTitle) }>Display title capitalized</button>
</div>
)
}
Code language: JavaScript (javascript)
In the above example, in the ChildComponent, we call the capitalizeTitle method inside the ParentComponent. We needed to pass the method via prop to access it.
Please note that we cannot call the function directly as onClick={capitalizeTitle(someTitle)}. This is because, at this stage, JavaScript will directly call the capitalizeTitle as soon as the application is mounted. We want to call it only when the user clicks on the button, hence we use an anonymous function.