0

This is child component

import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import leftNavigation from '../actions/leftNavigation';

class AddBorrowers extends Component {
     constructor(props){
        super(props);
     }

     render(){
          return(
             <div className={this.props.classValue + ' ' + 'borrowerForm'} 
                onClick={() => {
                    this.props.sendActions('hide Add Borrrowers Form')
                }
             }>
             </div>
   )
 }

}

this is my BorrowersParent Controller

class BorrowersParent extends Component {
constructor(props){
     super(props); 
}

 sendActions (data) {
      switch(data){
          case 'hide Add Borrrowers Form':
              console.log(this.props);
          break;
      }
 }

  render(){
    return(
        <div className={this.props.borrowersParent}>
             <AddBorrowers classValue={this.props.addBorrowers} sendActions={this.sendActions}/>

        </div>
    );
  }

}

this is my mapStateToProps and mapDispatchToProps

function mapStateToProps(state) {
      return {
          addBorrowers: state.parentReducer.ui_state.addBorrowers,
}}

function mapDispatchToProps(dispatch){
      return bindActionCreators({
            leftNavigation: leftNavigation}, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(BorrowersParent);

Note: Both AddBorrowers Component and BorrowersParent are located in same file.

On triggering onClick in the AddBorrowers component, 'this.props' keeps on returning undefined from the sendActions method located in BorrowersParent.

please I need to stop getting undefined from 'this.props', how do I accomplish this?? I need onClick event to trigger a dispatch()??

Estus Flask
  • 206,104
  • 70
  • 425
  • 565

1 Answers1

0

Either you use arrow function on sendActions:

 sendActions = (data) => {
      switch(data){
          case 'hide Add Borrrowers Form':
              console.log(this.props);
          break;
      }
 }

or you bind this method in constructor:

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

Without the above, the context of this changes during the click event, and therefore this.props doesn't exist.

Liren Yeo
  • 3,215
  • 2
  • 20
  • 41