Earlier we saw how we can call a function in the parent component from a child component using an anonymous function in the child component.
In this example, we will learn how we can call a function in the parent component with the help of a local function or inner function in the child component.
Assume that we have a function named capitalizeTitle which capitalizes and prints the title in the parent component.
We can create a function named capitalizeTitleChild in the child component which calls the capitalizeTitle function in the parent component.
const ParentComponent = () => {
function capitalizeTitle(someTitle) {
alert(someTitle.toUpperCase())
}
return (
<ChildComponent capitalizeTitle={capitalizeTitle} someTitle={'Hello there!'} />
)
}
const ChildComponent = ({ capitalizeTitle, someTitle }) => {
function capitalizeTitleChild() {
capitalizeTitle(someTitle)
}
return (
<div>
<h2>{someTitle}</h2>
<button onClick={capitalizeTitleChild}>Display title capitalized</button>
</div>
)
}
Code language: JavaScript (javascript)
In the above example, we have a local function named capitalizeTitleChild which calls the capitalizeTitle function passed as a prop from the parent component.