-1

i have two components:

Parent.js

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

function Parent() {

return (
    <div> 
         <Child />
         <button onClick={invoke child method onClick} > Button </button>
    </div>
 )
}

export default Parent

Child.js

import React from 'react

class Child extends Component {

getAlert() {
    console.log("called from parent")
}

render() {
    return (
        <div> 
          This is from child
        </div>
    )
  }
}

export default Child

Now, I want to call getAlert() method from parent component we can say i want to call a child method from parent. Please notice Parent is functional and child is class.

devspartan
  • 594
  • 7
  • 15
  • 1
    It doesn't work that way. Components are not "instantiated" like that, so you don't really have a reference to the component to invoke methods on. What you should instead do is pass down a function or whatever you would like to the child component through it's props, which the child component can then use. – nbokmans Jan 06 '21 at 10:45
  • 1
    Why does the method live in the child if the parent needs to access it? – evolutionxbox Jan 06 '21 at 10:48
  • Because getAlert() will perform action on child component data. It's just a prototype. – devspartan Jan 06 '21 at 10:49
  • Does this answer your question? [Call child method from parent](https://stackoverflow.com/questions/37949981/call-child-method-from-parent) – sayalok Jan 06 '21 at 10:50
  • @sayalok Nope here child and parent are of same type. functional-functional and class-class. Here is difference. – devspartan Jan 06 '21 at 10:51

1 Answers1

0

Here is how you can do it.

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

function Parent() {
  const handleAlert=(paramfn?:any)=>{
     if(paramfn){
         paramfn();
     }
  }

return (
    <div> 
         <Child onAlert={handleAlert} />
         <button onClick={invoke child method onClick} > Button </button>
    </div>
 )
}

export default Parent

/*********Child**********/

import React from 'react'

class Child extends Component {

getAlert() {
    console.log("called from parent")
}

render() {
    return (
        <div onClik ={()=>this.props.onAlert(getAlert);}> 
          This is from child
        </div>
    )
  }
}

export default Child
Sam
  • 1,040
  • 1
  • 7
  • 11
  • As far as I can see You are invoking the child method by clicking on the div of child. Just passing the method as argument for parent method( onAlert ) and executing in parent. But what I want is click in parent and execute in child. Let us suppose child is a drawer which is hidden for now, Then how will you click on div(This is from child) and invoke method. – devspartan Jan 06 '21 at 18:01
  • It is already answered here https://stackoverflow.com/questions/37949981/call-child-method-from-parent – Sam Jan 07 '21 at 11:29