0

Why in the first example does the constructor not need a binding statement, but it is needed in the second example? To me they look functionally the same.

    import React from 'react';

    export class Car extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          color: "red"
        };
      }
      changeCarColor = () => {
        const newCarColor = this.state.color === "red" ? "blue" : "red";
        this.setState({color: newCarColor});
      }
      render() { 
        return (
          <div>
            <p>
              My car is {this.state.color}
            </p>
            <button type="button" onClick={this.changeCarColor}>
                Change color
            </button>
          </div>
        );
      }
    }
    import React from 'react';

    const green = '#39D1B4';
    const yellow = '#FFD712';

    export class Toggle extends React.Component {
      constructor(props) {
        super(props);
        this.state = {color: green};
        this.changeColor = this.changeColor.bind(this);
      }

      changeColor() {
        const newColor = this.state.color === green ? yellow : green;
        this.setState({ color: newColor });
      }

      render() {
        return (
          <div style={{background: this.state.color}}>
            <h3>
              Change my color
            </h3>
            <button onClick = {this.changeColor}>
               Change color
            </button>
          </div>
        );
      }
    }

I tried removing the bind statement from the second example and it stopped functioning.

Apostolos
  • 10,033
  • 5
  • 24
  • 39
KRawl
  • 1
  • 1

0 Answers0