Search code examples
reactjsapexcharts

React.js - Cannot read property of undefined, even though context is bound (call parent method from child)


I am building a small app in React -- trying to call a function from my parent component Job when a bar from a bar chart (ApexCharts) is clicked in a child component SummaryChart.

Naturally, the way I have read to do this is to define a function in Job called getSequenceView, and pass it in a prop to Chart under the alias handleBarClick, then call this.props.handleBarClick from SummaryChart to invoke it in the parent.

Parent Component

class Job extends Component {
  constructor(props)
  {
    super(props);

    this.state = {
      ...
    }

    this.getSequenceView = this.getSequenceView.bind(this);

  }

  getSequenceView(config, event)
  {
    console.log(config.someData);
    $('#help-modal').modal();
  }

render()
  {
    return (
      
      <SummaryChart
        handleBarClick={this.getSequenceView}
      />

    );
  }

Child Component

class SummaryChart extends Component {
  constructor(props) {

    super(props);

    this.state = {
      options: {
        chart: {
          events: {
            dataPointSelection:  function(event, chartContext, config) {
              this.props.handleBarClick();
            },
        }
     }
  }

  render() {
    return (

          <Chart
            options={this.state.options}
            series={this.state.series}
            type="bar"
            width="100%"
          />
    );
  }
}

ApexCharts docs for handling events here!

I have a feeling that since I am passing this.state.options as a prop to the actual Chart object from ApexCharts that when the bar is clicked, the event registers from the Chart object instead of SummaryChart and perhaps that is why I am receiving the error.

app.js:66798 Uncaught TypeError: Cannot read property 'handleBarClick' of undefined


Solution

  • Issue

    In the constructor this.props hasn't been set yet.

    Solution

    Access the props that were passed to the constructor.

    constructor(props) {
      super(props);
    
      this.state = {
        options: {
          chart: {
            events: {
              dataPointSelection: function (event, chartContext, config) {
                props.handleBarClick();
              }
            }
          }
        }
      };
    }