Coding is Life
Coding is Life

Reputation: 53

How to call child method inside parent component? React-redux

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);

Upvotes: 0

Views: 7511

Answers (2)

Diego Segura
Diego Segura

Reputation: 1033

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} />

}

Upvotes: 2

Nithish
Nithish

Reputation: 6009

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

Upvotes: 2

Related Questions