Search code examples
reactjsreact-propsreact-component

How to pass props from child component to its parent of parent?


Suppose I have three components, where SubMain2 is inside SubMain1 and SubMain1 is inside Main. How would I pass props from SubMain2 to Main component?

PROBLEM: TypeError: Cannot read property 'handleSubMain1' of undefined

Main

class Main extends Component {
  constructor(props) {
  super(props);
  this.handleSubMain1 = this.handleSubMain1.bind(this);
  }

 handleSubMain1() {
  console.log('received props from SubMain1 which is from SubMain2!');
 }

  render() {
     <SubMain1 handleSubMain1={this.handleSubMain1}/>
  }
}

SubMain1

class SubMain1 extends Component {

 constructor(props) {
 super(props);
 this.handleSubMain2 = this.handleSubMain2.bind(this);
 }

 handleSubMain2() {
  console.log('received props from SubMain2!');
 }

  render() {
     <SubMain2 handleSubMain2={this.handleSubMain2}/>
  }
}

SubMain2

Component SubMain2 extends Component {
   constructor(props) {
   super(props);
   }

   render() {
     this.props.handleSubMain2();
  }
}

I tried this approach, however I'm getting handleSubMain1 function is undefined. I even tried passing props from SubMain2 to Main component directly, however no luck.


Solution

  • here is the sandbox I made so you can see the console log : https://codesandbox.io/s/funny-chebyshev-n5srl?file=/src/App.js:63-717

    here is the code in case you need it here:

    
    class Main extends Component {
      handleSubMain1(arg) {
        console.log('received props from SubMain1 which is from SubMain2!');
        console.log(arg);
     }
    
      render() {
         return <SubMain1 handleSubMain1={this.handleSubMain1}/> 
      }
    }
    
    class SubMain1 extends Component {
      render() {
         return <SubMain2 handleSubMain2={this.props.handleSubMain1}/>
      }
    }
    
    class SubMain2 extends Component {
      handleClick(){
        this.props.handleSubMain2('any thing I pass as an argument I can access it in main');
      }
    
      render() {
         return (
           <button onClick={this.handleClick.bind(this)}>
             Click me to send data to Main
           </button>
         )
     }
    }