Listing 7-8: Writing and binding an event handler method in a class
The Coffee Maker is off.import {Component} from 'react';
class CoffeeMachine extends Component {
constructor(props){
super(props);
this.state={
brewing:false
}
this.toggleBrewing = this.toggleBrewing.bind(this);
}
toggleBrewing = function(){
this.setState({brewing:!this.state.brewing});
}
render(){
return(
<>
The Coffee Maker is {this.state.brewing?'on':'off'}.<br />
<button onClick={this.toggleBrewing}>toggle brewing state</button>
</>
);
}
}
export default CoffeeMachine;
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.