0

How to call child method inside parent component?

Code is more complicated, but I did my best to simplify it for u guys.

const Parent = (history) => {

function triggerChildMethod (e) {

}


return (
          <div> 
                <Child history={history}/> 
         </div>
       )
}



function mapStateToProps(state){    //I used redux here and inside child too
    return {state};
}

function mapDispatch (){
    ...       /// I just simplified here
}

export default connect(mapStateToProps, mapDispatch)(Parent);

Child have one method that needs to be call from parent:

class Child extends React.Component{

function needsToBeCalled = () => {

    }
}

mapStateToProps(state){
return {blabla: state};
}

export default connect(mapStateToProps, mapDispatch)(PostsList);

Coding is Life
  • 57
  • 3
  • 10
  • basically it kinds of impossible to send props from child to the parent. Can you tell more about the context, what is your goal to do so? I'm pretty sure there is another way to solve your problem instead of sending props from child to parent – Devin Ekadeni Jun 12 '20 at 13:22

2 Answers2

2

You can use refs for calling Child component method in Parent component. Consider there's this method needsToBeCalled in the child and that need to be called from parent

class Parent extends React.Component {

  constructor(props) {
    super(props);
    this.childRef = React.createRef();
  }

  function triggerChildMethod (e) {
    this.childRef.current.needsToBeCalled()
  }

  render() {
     return (
        <div> 
           <Child ref={this.childRef}/> 
        </div>)
   }
}

//Remaining code

Hope this helps

Nithish
  • 5,393
  • 2
  • 9
  • 24
  • Using redux will not be a problem, It'll still work. If you can use hooks then `useRef` and if not is there any problem if needed to converted as a class component. – Nithish Jun 12 '20 at 16:27
2

Check this answer

The one marked as solved is a deeper explanation over what Nitish answered. And the next one is the correct way of doing it.

Generally speaking, you should try to stick to this pattern

enter image description here

So you could just define your function in your parent and pass it as prop to the child.

function ParentComponent() {
 function doFoo() { 
    // your code
 }

 return <ChildComopnent onFoo={doFoo} />

}

Diego Segura
  • 896
  • 6
  • 17