React Counter
by Allie Yu
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Babel + JSX
/*
* A simple React component
*/
class App extends React.Component {
state = { count: 0 };
/* increment = () => {
this.setState({
count: this.state.count + 1
});
};
decrement = () => {
this.setState({
count: this.state.count - 1
});
}; */
increment = () => {
this.setState((prevState) => ({ count: prevState.count + 1 }));
}
decrement = () => {
this.setState((prevState) => ({ count: prevState.count - 1 }));
}
render() {
return (
<div>
<h2>Counter</h2>
<div>
<button onClick={this.decrement}>-</button>
<span>{this.state.count}</span>
<button onClick={this.increment}>+</button>
</div>
</div>
);
}
}
/*
* Render the above component into the div#app
*/
ReactDOM.render(<App />, document.getElementById('root'));