Skip to content

Instantly share code, notes, and snippets.

@RanjanSushant
Created April 7, 2022 13:28
Show Gist options
  • Save RanjanSushant/485b25da9e1386a019edae0ffda0d32d to your computer and use it in GitHub Desktop.
Save RanjanSushant/485b25da9e1386a019edae0ffda0d32d to your computer and use it in GitHub Desktop.
Codesphere React Native Demo ToDo App
import React from "react";
import {
KeyboardAvoidingView,
StyleSheet,
Text,
View,
TextInput,
TouchableOpacity,
Keyboard,
ScrollView,
} from "react-native";
import Task from "./Task";
export default function App() {
const [task, setTask] = React.useState();
const [taskItems, setTaskItems] = React.useState([]);
function handleAddTask() {
Keyboard.dismiss();
setTaskItems([...taskItems, task]);
setTask(null);
}
function completeTask(index) {
let itemsCopy = [...taskItems];
itemsCopy.splice(index, 1);
setTaskItems(itemsCopy);
}
return (
<View style={styles.container}>
{/* Scroll view to enable scrolling when list gets longer than the page */}
<ScrollView
contentContainerStyle={{
flexGrow: 1,
}}
keyboardShouldPersistTaps="handled"
>
{/* Today's Tasks */}
<View style={styles.tasksWrapper}>
<Text style={styles.sectionTitle}>My ToDo List</Text>
<View style={styles.items}>
{/* This is where the tasks will go! */}
{taskItems.map((item, index) => {
return (
<TouchableOpacity
key={index}
onPress={() => completeTask(index)}
>
<Task text={item} />
</TouchableOpacity>
);
})}
</View>
</View>
</ScrollView>
{/* Write a task */}
{/* Uses a keyboard avoiding view which ensures the keyboard does not cover the items on screen */}
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.writeTaskWrapper}
>
<TextInput
style={styles.input}
placeholder={"Add new item"}
value={task}
onChangeText={(text) => setTask(text)}
/>
<TouchableOpacity onPress={() => handleAddTask()}>
<View style={styles.addWrapper}>
<Text style={styles.addText}>+</Text>
</View>
</TouchableOpacity>
</KeyboardAvoidingView>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#E5E5E5",
},
tasksWrapper: {
paddingTop: 80,
paddingHorizontal: 20,
},
sectionTitle: {
fontSize: 24,
fontWeight: "bold",
},
items: {
marginTop: 30,
},
writeTaskWrapper: {
position: "absolute",
bottom: 60,
width: "100%",
flexDirection: "row",
justifyContent: "space-around",
alignItems: "center",
},
input: {
paddingVertical: 15,
paddingHorizontal: 15,
backgroundColor: "#FFF",
width: 250,
},
addWrapper: {
width: 60,
height: 60,
backgroundColor: "#FFF",
justifyContent: "center",
alignItems: "center",
},
addText: {},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment