Skip to content

Instantly share code, notes, and snippets.

@TheBojda
Created May 30, 2021 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheBojda/2fecf39b0f2da03d0ce0cca404f01c1d to your computer and use it in GitHub Desktop.
Save TheBojda/2fecf39b0f2da03d0ce0cca404f01c1d to your computer and use it in GitHub Desktop.
Simple todo example in react native using typescript and state hooks
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, Platform, Keyboard, Button, FlatList, TextInput } from 'react-native';
const isAndroid = Platform.OS == "android";
export default function App() {
const [text, setText] = useState('');
const [tasks, setTasks] = useState([{ key: '0', text: "First task" }]);
const [viewPadding, setViewPadding] = useState(0);
useEffect(() => {
Keyboard.addListener(isAndroid ? "keyboardDidShow" : "keyboardWillShow", e => setViewPadding(e.endCoordinates.height + 10));
Keyboard.addListener(isAndroid ? "keyboardDidHide" : "keyboardWillHide", () => setViewPadding(10));
});
const changeTextHandler = (text: string) => {
setText(text);
};
const addTask = () => {
if (text.trim().length > 0) {
setTasks(tasks.concat({ key: tasks.length.toString(), text: text }));
setText('');
}
}
const deleteTask = (index: number) => {
let tasksCopy = tasks.slice();
tasksCopy.splice(index, 1);
setTasks(tasksCopy);
}
const listItem = (props: any) => {
return (
<View>
<View style={styles.listItemCont}>
<Text style={styles.listItem}>
{props.item.text}
</Text>
<Button title="X" onPress={() => deleteTask(props.index)} />
</View>
<View style={styles.hr} />
</View>
);
}
return (
<View style={[styles.container, { paddingBottom: viewPadding }]}>
<FlatList
style={styles.list}
data={tasks}
renderItem={listItem} />
<TextInput
style={styles.textInput}
onChangeText={changeTextHandler}
onSubmitEditing={addTask}
value={text}
placeholder="Add Tasks"
returnKeyType="done"
returnKeyLabel="done" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#F5FCFF",
padding: 10,
paddingTop: 30
},
list: {
width: "100%"
},
listItem: {
paddingTop: 2,
paddingBottom: 2,
fontSize: 18
},
hr: {
height: 1,
backgroundColor: "gray"
},
listItemCont: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between"
},
textInput: {
height: 40,
paddingRight: 10,
paddingLeft: 10,
borderColor: "gray",
borderWidth: isAndroid ? 0 : 1,
width: "100%"
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment