Skip to content

Latest commit

 

History

History
22 lines (14 loc) · 987 Bytes

use-class-properties-to-simplify-handlers.md

File metadata and controls

22 lines (14 loc) · 987 Bytes

Use class properties to simplify handler functions

In JavaScript, class methods are not bound to class instances by default. In React, that means using either .bind() or an arrow function onClick={(e) => this.handleClick(e)} to pass this.

Alternately, use Class properties. From the React documentation:

class LoggingButton extends React.Component {

	handleClick = () => {
		console.log('this is:', this);
	}

}

This syntax ensures that handleClick has the correct this value when called.

In some cases, properties remove the need for constructors in a class. See an example of how this works in an article by Dale Jefferson.

Originally prompted by reading Mapbox React examples code.