Skip to content

Instantly share code, notes, and snippets.

@carlosvega20
Forked from gaearon/Counter.js
Last active November 1, 2016 14:15
Show Gist options
  • Save carlosvega20/c4212293d81fdc0660eadcbfe01aa495 to your computer and use it in GitHub Desktop.
Save carlosvega20/c4212293d81fdc0660eadcbfe01aa495 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
const counter = (state = { value: 0 }, action) => {
switch (action.type) {
case 'INCREMENT':
return { value: state.value + 1 };
case 'DECREMENT':
return { value: state.value - 1 };
default:
return state;
}
}
class Counter extends Component {
state = counter(undefined, {});
dispatch(action) {
this.setState(prevState => counter(prevState, action));
}
increment = () => {
this.dispatch({ type: 'INCREMENT' });
};
decrement = () => {
this.dispatch({ type: 'DECREMENT' });
};
render() {
return (
<div>
{this.state.value}
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
</div>
)
}
}
// Or
import React, { Component } from 'react';
class Counter extends Component {
state = { value: 0 };
increment = () => {
this.setState(prevState => ({
value: prevState.value + 1
}));
};
decrement = () => {
this.setState(prevState => ({
value: prevState.value - 1
}));
};
render() {
return (
<div>
{this.state.value}
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment