How to avoid using binding in react using es6?

Viewed 85

i am using window.onerror to log javascript errors to a file like in code below,

class ErrorComponent extends react.purecomponent {
    constructor(props) {
        super(props);
        this.handle_error = this.handle_error.bind(this);
    }

    componentDidMount = () => {
        window.onerror = this.handle_error;
    }

    handle_error = (message, source, lineno, colno, error) => {
        const payload = {
            'message': message,
            'source': source,
        };
        return false;
    }

    render = () => {
        return null;
    }
}

So from above code it is seen i have used bind. if i dont bind handle_error and call like below in componentdidmount

componentDidMount () {
    window.onerror = this.handle_error();
}

And when i log the the message and source values in handle_error i get them as undefined.

How can i solve it...I dont want to use bind and how can i fix this without binding handle_error method. could someone help me with this. thanks.

2 Answers

Use a fat arrow function

The fat arrow function should also pass the this context to the handle_error function.

class ErrorComponent extends react.purecomponent {
    componentDidMount = () => {
        window.onerror = (message, source, lineno, colno, error) => this.handle_error(message, source, lineno, colno, error);
    }

    handle_error = (message, source, lineno, colno, error) => {
        const payload = {
            'message': message,
            'source': source,
        };
        return false;
    }

    render = () => {
        return null;
    }
}

The 'problem' or inconvenience you are facing is one of the very reasons arrow function expression (aka 'fat arrow function') was implemented.

You can read more about them here.

Your example code using arrow function expression is below. Please note passing arguments onerror.

class ErrorComponent extends react.purecomponent {
  componentDidMount = () => {
    window.onerror = (message, source, lineno, colno, error) => this.handle_error(message, source, lineno, colno, error);
  }

  handle_error = (message, source, lineno, colno, error) => {
    const payload = {
      'message': message,
      'source': source,
    };
    return false;
  }

  render = () => {
    return null;
  }
}

Related