Skip to content

Instantly share code, notes, and snippets.

@nivla
Created December 16, 2015 20:30
Show Gist options
  • Save nivla/1c34ef513640772059c7 to your computer and use it in GitHub Desktop.
Save nivla/1c34ef513640772059c7 to your computer and use it in GitHub Desktop.
List counter using react and redux.
import {createStore} from 'redux';
import React from 'react';
import ReactDOM from 'react-dom';
const todoApp = (state = [0], action) => {
switch (action.type) {
case 'INCREMENT':
return [
...state.slice(0, action.index),
state[action.index] + 1,
...state.slice(action.index + 1)];
case 'DECREMENT':
return [
...state.slice(0, action.index),
state[action.index] - 1,
...state.slice(action.index + 1)];
case 'ADD_COUNTER':
return [...state, 0];
default:
return state;
};
};
const store = createStore(todoApp);
const Counter = ({
value,
onIcrement,
onDecrement
}) => {
return(
<div>
<h1>{value}</h1>
<button onClick={onIcrement}>+</button>
<button onClick={onDecrement}>-</button>
</div>
);
};
class CounterApp extends React.Component {
render() {
return(
<div>
{store.getState().map((val,i) =>
<div>
<Counter value={val} onIcrement={() =>
store.dispatch({
type: "INCREMENT",
index: i
})
}
onDecrement={() =>
store.dispatch({
type: "DECREMENT",
index: i
})
}
/>
</div>
)}
<button onClick={e =>
store.dispatch({
type: 'ADD_COUNTER'
})
}>
Add Counter
</button>
</div>
);
}
}
const render = () => {
ReactDOM.render(<CounterApp />, document.getElementById("counter"));
};
store.subscribe(render);
render();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment