-2

I'm trying to child to parent communication so, i'm using props. There's have a little problem. I get an error when I use the StatusChanged() function.

There is my parent (App.JS) file:

class App extends Component {

  constructor(props) {
    super(props);
    this.state = { trackingStatus: true };
  }

  trackingStatusUpdate(data)
  {
      console.log(data);
  }

  render() {
    return (
      <div className="App">
        <Switcher trackingStatus={this.state.trackingStatus} trackingStatusUpdate={this.trackingStatusUpdate} />
      </div>
    );
  }
}

And There is my child (Switcher.JS) file:

class Switcher extends Component {


    constructor(props) {
        super(props);
        this.state = {
            trackingStatus: this.props.trackingStatus
        };
    }   


    statusChanged()
    {
        this.props.trackingStatusUpdate(this.state.trackingStatus);
    }

    render() {
        return (
            <div>
                <h3>Tracking Mode</h3>
                <label className="switch">
                  <input type="checkbox" defaultChecked={this.state.trackingStatus} onChange={this.statusChanged}  id="switch"  />
                  <div className="slider round"></div>
                </label>
            </div>
        );
    }

}

Switcher.defaultProps = {
    trackingStatus: true
}

What is the problem?

Thank you.

Rys
  • 479
  • 1
  • 6
  • 18

1 Answers1

1

You need to bind the trackingStatusUpdate() and statusChanged() class methods…

class App extends Component{
  constructor(props){
    super(props);
    this.state = {trackingStatus: true};

    this.trackingStatusUpdate = this.trackingStatusUpdate.bind(this);
  }

  ...
}

class Switcher extends Component{
  constructor(props){
    super(props);
    this.state = {trackingStatus: this.props.trackingStatus};

    this.statusChanged = this.statusChanged.bind(this);
  }

  ...
}
Shammel Lee
  • 4,092
  • 1
  • 17
  • 20