Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save etienne-dldc/fbe6d54d72eafaa441e354cbaa1a4edb to your computer and use it in GitHub Desktop.
Save etienne-dldc/fbe6d54d72eafaa441e354cbaa1a4edb to your computer and use it in GitHub Desktop.
10 - Multiple Counters - State in Counters
const Counter = props =>
<div>
<span>{props.value}</span>
{props.value > 0 &&
<button
onClick={() => {
// what should we do here ?
}}
>
-
</button>}
{props.value < 10 &&
<button
onClick={() => {
// what should we do here ?
}}
>
+
</button>}
</div>;
class Counters extends React.Component {
constructor(props) {
super(props);
this.state = {
counters: [0, 0, 0]
};
}
render() {
return (
<div>
<button
onClick={() => {
// like push be we create a new array
this.setState(prevState => ({
counters: [...prevState.counters, 0]
}));
}}
>
Add counter
</button>
<br />
<div>
{this.state.counters.map((value, index) => <Counter value={value} />)}
</div>
</div>
);
}
}
ReactDOM.render(<Counters />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment