Untitled
unknown
plain_text
10 months ago
3.5 kB
4
Indexable
import React, { useState } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity, FlatList } from 'react-native';
import { MaterialIcons } from '@expo/vector-icons';
interface TodoItem {
id: string;
title: string;
completed: boolean;
}
const HomeScreen = () => {
const [todo, setTodo] = useState("");
const [todolist, setTodolist] = useState<TodoItem[]>([]);
const [edittodo, setEdittodo] = useState<TodoItem | null>(null);
const handleAddTodo = () => {
if (todo.trim() === "") return;
if (edittodo) {
// Edit mode: Update the existing todo
const updatedTodoList = todolist.map((item) =>
item.id === edittodo.id ? { ...item, title: todo } : item
);
setTodolist(updatedTodoList);
setEdittodo(null); // Exit edit mode
} else {
// Add mode: Add a new todo
setTodolist([...todolist, { id: Date.now().toString(), title: todo, completed: false }]);
}
setTodo(""); // Clear the input field
};
const handledeletetodo = (id: string) => {
const updatedTodoList = todolist.filter((item) => item.id !== id);
setTodolist(updatedTodoList);
};
const handleedittodo = (todo: TodoItem) => {
setEdittodo(todo);
setTodo(todo.title);
};
const todocompletion = (id: string) => {
const updatedTodoList = todolist.map((item) =>
item.id === id ? { ...item, completed: !item.completed } : item
);
setTodolist(updatedTodoList);
};
const renderTodos = ({ item, index }: { item: TodoItem; index: number }) => {
return (
<View
style={{
backgroundColor: "#1e90ff",
borderRadius: 6,
paddingHorizontal: 6,
paddingVertical: 12,
marginBottom: 12,
flexDirection: "row",
alignItems: "center"
}}>
<TouchableOpacity onPress={() => todocompletion(item.id)} style={{ flex: 1 }}>
<Text style={{
color: "#fff",
fontSize: 20,
fontWeight: "800",
flex: 1,
textDecorationLine: item.completed ? "line-through" : "none",
}}>{item.title}</Text>
</TouchableOpacity>
<MaterialIcons name="edit" size={24} color="blue" onPress={() => handleedittodo(item)} />
<MaterialIcons name="delete" size={24} color="red" onPress={() => handledeletetodo(item.id)} />
</View>
);
};
return (
<View>
<TextInput
style={{
borderWidth: 2,
borderColor: "blue",
borderRadius: 6,
paddingVertical: 6,
paddingHorizontal: 16
}}
placeholder='add task'
value={todo}
onChangeText={(userText) => setTodo(userText)}
/>
<TouchableOpacity
style={{
backgroundColor: "#000",
borderRadius: 6,
paddingVertical: 12,
marginTop: 24,
alignItems: "center"
}}
onPress={handleAddTodo}
>
<Text style={{
color: "#fff",
fontWeight: "bold",
fontSize: 20
}}>
{edittodo ? "Update" : "Add"}
</Text>
</TouchableOpacity>
<FlatList
data={todolist}
renderItem={renderTodos}
keyExtractor={(item) => item.id}
style={{ marginTop: 20 }}
/>
</View>
);
};
const styles = StyleSheet.create({});
export default HomeScreen;Editor is loading...
Leave a Comment