Search code examples
reactjsreact-functional-componentprop

React funcional component calling function from another component


I have two buttons named selectall in two different components . in Acompoent I am having selectall button and its selectall function. I am trying to call this selectall function from Bcompoent. Here Bcompoent and Acompoent has relation with Ccompoent. can someone tell me how to trigger selectAll from Bcompoent.

Acompoent

 selectAll={selectAll}

  const selectAll = (e) => { console.log ("selectAll")}

Solution

  • For this you will need to pass a method from your parent component to both A & B components like so:

    class Parent extends React.Component{
     .
     .
     .
     selectAll = (data) => {
      console.log({data});
     }
    
     render(){
      return(
       <ComponentA selectAll={this.selectAll}  />
       <ComponentB selectAll={this.selectAll} />
      )
     }
    }
    
    
    
    class ComponentA extends React.Component{
     .
     .
     .
     render(){
      return(
        <button onClick={() => this.props.selectAll(data)>click me</button>
      )
     }
    }
    
    class ComponentB extends React.Component{
     .
     .
     .
     render(){
      return(
        <button onClick={() => this.props.selectAll(data)>click me</button>
      )
     }
    }