Skip to content

Instantly share code, notes, and snippets.

Last active December 17, 2019 10:17
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Given the code defined above, can you identify two problems?
The constructor does not pass its props to the super class. It should include the following line:
constructor(props) {
// ...
The event listener (when assigned via addEventListener()) is not properly scoped because ES2015 doesn’t provide autobinding. Therefore the developer can re-assign clickHandler in the constructor to include the correct binding to this:
constructor(props) {
this.clickHandler = this.clickHandler.bind(this);
// ...
class MyComponent extends React.Component {
constructor(props) {
// set the default internal state
this.state = {
clicks: 0
componentDidMount() {
this.refs.myComponentDiv.addEventListener('click', this.clickHandler);
componentWillUnmount() {
this.refs.myComponentDiv.removeEventListener('click', this.clickHandler);
clickHandler() {
clicks: this.clicks + 1
render() {
let children = this.props.children;
return (
<div className="my-component" ref="myComponentDiv">
<h2>My Component ({this.state.clicks} clicks})</h2>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment