Skip to content

Instantly share code, notes, and snippets.

@anthonybrown
Last active November 9, 2017 05:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonybrown/dd47f481f77115b83ffa12cd292aa75b to your computer and use it in GitHub Desktop.
Save anthonybrown/dd47f481f77115b83ffa12cd292aa75b to your computer and use it in GitHub Desktop.
A simple Button component using React and stage2 and 3 JavaScript Proposals
/* Using the stage 2 way */
class Button extends React.Component {
state = { counter: 0 };
/*
** This might cause a race condition later on
** because setState is an asynchronous call and
** will be batched with other setState calls for performance.
*/
/*
* we can define handleClick as an instance property
* again, we are using the modern syntax version here
* that allows us to use the arrow function whcih binds
* our `this` keyword for us. // look at the constructor method
* in the other variation of this component.
*/
// handleClick = () =>
// this.setState({
// counter: this.state.counter + 1
// });
/*
* we can avoid any race conditions by
* using `prevState` and return a function
*/
handleClick = () => {
// this.setState((prevState) => {
// return {
// counter: prevState.counter += 1
// }
// })
/* wrap the function with parenthesis */
this.setState((prevState) => ({
counter: prevState.counter += 1
}))
}
render() {
return (
<button onClick={ this.handleClick }>
{this.state.counter}
</button>
);
}
}
/* A more traditional way */
/* Using the stage 3 way */
// class Button extends React.Component {
// constructor(props) {
// super(props)
// this.state = { counter: 0 }
// this.handleClick = this.handleClick.bind()
// }
// handleClick = () =>
// this.setState({
// counter: this.state.counter + 1
// })
// render() {
// return (
// <button onClick={this.handleClick}>
// {this.state.counter}
// </button>
// );
// }
// }
/* mountNode is a global for the repl I was a using */
ReactDOM.render(<Button />, mountNode)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment