-
Notifications
You must be signed in to change notification settings - Fork 41
/
todoapp.js
122 lines (112 loc) · 2.63 KB
/
todoapp.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
import React, { Component } from 'react';
import {
ListView,
StyleSheet,
Switch,
Text,
TouchableOpacity,
View
} from 'react-native';
class TodoApp extends Component {
constructor(...args) {
super(...args)
// Set the initial state.
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 != r2
}),
onlyShowNotDone: false,
todos: [
this.makeTodo(3),
this.makeTodo(2, true),
this.makeTodo(1)
]
}
}
addTodo() {
// Inject a new todo at the start of the list.
this.setState({
todos: [this.makeTodo(), ...this.state.todos]
});
}
makeTodo(number, done) {
const id = number ? number : this.state.todos.length + 1;
return {
id: id,
done: done ? true : false,
text: 'Todo Item #' + id
}
}
toggleTodo(todo) {
let newTodo = {...todo};
newTodo.done = !todo.done;
const index = this.state.todos.indexOf(todo);
// Recreate a list but replace the existing one.
let todos = [...this.state.todos.slice(0, index), newTodo, ...this.state.todos.slice(index + 1)];
this.setState({
todos: todos
});
}
renderTodo(todo) {
return (
<View style={styles.todo} key={todo.id}>
<View>
<Switch onValueChange={() => this.toggleTodo(todo)} value={todo.done} />
</View>
<View>
<Text>{todo.text}</Text>
</View>
</View>
)
}
render() {
const todos = this.state.todos.filter((todo) => {
if (this.state.onlyShowNotDone) {
return !todo.done;
}
return true;
});
return (
<View style={styles.container}>
<View style={styles.options}>
<TouchableOpacity onPress={() => this.addTodo()} style={styles.add}>
<Text>+ Add a todo</Text>
</TouchableOpacity>
<View style={styles.hide}>
<Text>Hide done</Text>
<Switch
onValueChange={(value) => this.setState({onlyShowNotDone: value})}
value={this.state.onlyShowNotDone}/>
</View>
</View>
<ListView
dataSource={this.state.dataSource.cloneWithRows(todos)}
renderRow={this.renderTodo.bind(this)} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
add: {
flex: 1,
padding: 10
},
hide: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-around'
},
options: {
flexDirection: 'row'
},
todo: {
flex: 1,
flexDirection: 'row'
}
});
export default TodoApp;