-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathComponent.jsx
More file actions
59 lines (48 loc) · 1.64 KB
/
Component.jsx
File metadata and controls
59 lines (48 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import React from "react";
export default class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 0,
history: []
};
}
plus = () => {
this.setState((state) => this.updateState(state, 1));
};
minus = () => {
this.setState((state) => this.updateState(state, -1));
};
updateState = (state, k) => {
const value = state.value + k;
const item = {id: uniqueId(), value};
return {
value,
history: [item, ...state.history]
}
}
deleteItem = (item) => {
this.setState((state) => {
const history = state.history.filter(current => current.id !== item.id);
return {
value: history.length > 0 ? state.value : 0,
history
}
});
}
render() {
const list = this.state.history.map((item) => <button type="button" key={item.id} className="list-group-item list-group-item-action" onClick={() => this.deleteItem(item)}>{item.value}</button>);
return (
<div>
<div className="btn-group font-monospace" role="group">
<button type="button" className="btn btn-outline-success" onClick={this.plus}>+</button>
<button type="button" className="btn btn-outline-danger" onClick={this.minus}>-</button>
</div>
{this.state.history.length > 0 ? <div className="list-group">{list}</div> : null}
</div>
);
}
}
function uniqueId() {
return Math.random().toString(16).slice(2);
}