Call Parent Method From Child Component in React

hello friends, in this post i will tell you how you can call parent methods from child component

it is same as calling component’s function,

for example

import React from 'react'
import Child from './Child'

export default function Parent(){
    
    cons helloParent = () => {
        alert("hello from parent")
    }
    
    return (
        <>
	    <h2>This is parent component</h2>
        <Child parent={helloParent} />
        </>
    )
}

and this is child component

import React from 'react'
export default function Child( {parent} ){
    return (
    <button onClick={parent}>Call Parent</button>
    )
}

you can pass any argument to child component like we did in above parent contains refrence of helloParent() function so whenever child components onClick event triggered it will execute parent helloParent() function

comments powered by Disqus