-
Notifications
You must be signed in to change notification settings - Fork 918
/
Copy pathadd-remove.js
145 lines (140 loc) · 3.35 KB
/
add-remove.js
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import React, { Component } from 'react';
import SortableTree, { addNodeUnderParent, removeNodeAtPath } from '../src';
// In your own app, you would need to use import styles once in the app
// import 'react-sortable-tree/styles.css';
const firstNames = [
'Abraham',
'Adam',
'Agnar',
'Albert',
'Albin',
'Albrecht',
'Alexander',
'Alfred',
'Alvar',
'Ander',
'Andrea',
'Arthur',
'Axel',
'Bengt',
'Bernhard',
'Carl',
'Daniel',
'Einar',
'Elmer',
'Eric',
'Erik',
'Gerhard',
'Gunnar',
'Gustaf',
'Harald',
'Herbert',
'Herman',
'Johan',
'John',
'Karl',
'Leif',
'Leonard',
'Martin',
'Matt',
'Mikael',
'Nikla',
'Norman',
'Oliver',
'Olof',
'Olvir',
'Otto',
'Patrik',
'Peter',
'Petter',
'Robert',
'Rupert',
'Sigurd',
'Simon',
];
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
treeData: [{ title: 'Peter Olofsson' }, { title: 'Karl Johansson' }],
addAsFirstChild: false,
};
}
render() {
const getNodeKey = ({ treeIndex }) => treeIndex;
const getRandomName = () =>
firstNames[Math.floor(Math.random() * firstNames.length)];
return (
<div>
<div style={{ height: 300 }}>
<SortableTree
treeData={this.state.treeData}
onChange={treeData => this.setState({ treeData })}
generateNodeProps={({ node, path }) => ({
buttons: [
<button
onClick={() =>
this.setState(state => ({
treeData: addNodeUnderParent({
treeData: state.treeData,
parentKey: path[path.length - 1],
expandParent: true,
getNodeKey,
newNode: {
title: `${getRandomName()} ${
node.title.split(' ')[0]
}sson`,
},
addAsFirstChild: state.addAsFirstChild,
}).treeData,
}))
}
>
Add Child
</button>,
<button
onClick={() =>
this.setState(state => ({
treeData: removeNodeAtPath({
treeData: state.treeData,
path,
getNodeKey,
}),
}))
}
>
Remove
</button>,
],
})}
/>
</div>
<button
onClick={() =>
this.setState(state => ({
treeData: state.treeData.concat({
title: `${getRandomName()} ${getRandomName()}sson`,
}),
}))
}
>
Add more
</button>
<br />
<label htmlFor="addAsFirstChild">
Add new nodes at start
<input
name="addAsFirstChild"
type="checkbox"
checked={this.state.addAsFirstChild}
onChange={() =>
this.setState(state => ({
addAsFirstChild: !state.addAsFirstChild,
}))
}
/>
</label>
</div>
);
}
}