EN
React - simple TODO list app with adding and removing items on click
3 points
In this article, we would like to show you how to create simple TODO list app where you can add and remove items on click event in React.
It is simple list in which tasks are imposed in advance, the article only shows how to dynamically add new and remove existing tasks.
xxxxxxxxxx
1
// Note: Uncomment import lines while working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => {
6
const [list, setList] = React.useState(['task 1', 'task 2', 'task 3']);
7
const [id, setId] = React.useState(0);
8
9
const handleAddClick = () => {
10
setId(id => id + 1);
11
setList(list => [list, 'new task - ' + id]);
12
};
13
14
return (
15
<div>
16
<button onClick={handleAddClick}>Add item</button>
17
<div>
18
{list.map((item) => {
19
const handleRemoveClick = () => {
20
setList(list => list.filter((entry) => entry !== item));
21
};
22
return (
23
<div key={item} style={{ display: 'flex', border: '1px solid lightgray' }}>
24
{item}
25
<div style={{ flex: 1 }} /> {/* <-------------------- spacer element */}
26
<button onClick={handleRemoveClick}>x</button>
27
</div>
28
);
29
})}
30
</div>
31
</div>
32
);
33
};
34
35
const root = document.querySelector('#root');
36
ReactDOM.render(<App />, root);
Another example with clear list option:
xxxxxxxxxx
1
// Note: Uncomment import lines while working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => {
6
const [list, setList] = React.useState(['task 1', 'task 2', 'task 3']);
7
const [id, setId] = React.useState(0);
8
9
const handleAddClick = () => {
10
setId(id => id + 1);
11
setList(list => [list, 'new task - ' + id]);
12
};
13
14
const handleClear = () => {
15
setId(0);
16
setList([]);
17
};
18
19
return (
20
<div>
21
<div style={{ display: 'flex'}}>
22
<button onClick={handleAddClick}>Add item</button>
23
<button onClick={handleClear}>Clear list</button>
24
</div>
25
<div>
26
{list.map((item) => {
27
const handleRemoveClick = () => {
28
setList(list => list.filter((entry) => entry !== item));
29
};
30
return (
31
<div key={item} style={{ display: 'flex', border: '1px solid lightgray' }}>
32
{item}
33
<div style={{ flex: 1 }} /> {/* <-------------------- spacer element */}
34
<button onClick={handleRemoveClick}>x</button>
35
</div>
36
);
37
})}
38
</div>
39
</div>
40
);
41
};
42
43
const root = document.querySelector('#root');
44
ReactDOM.render(<App />, root);