Skip to main content

Mark as completed

We can pass in multiple styles to the same component by using a styles array, such as style={[styles.one, styles.two]}

Any of the array items can be undefined (so style={[styles.one, undefined]} is valid) and this is makes it easy to add conditional styles.

Let's add an optional isCompleted prop to the ShoppingList component and display a greyed out UI then the item is "completed".

First, let's add grey and a light grey (#eee) to our theme colors:

Update: theme.ts
@@ -2,4 +2,6 @@ export const theme = {
colorCerulean: "#1a759f",
colorWhite: "#fff",
colorBlack: "#000",
+ colorGrey: "grey",
+ colorLightGrey: "#eee",
};

Update the ShoppingListItem to have a "completed" UI id the isCompleted prop is true:

Update: components/ShoppingListItem.tsx
@@ -3,9 +3,10 @@ import { theme } from "../theme";

type Props = {
name: string;
+ isCompleted?: boolean;
};

-export function ShoppingListItem({ name }: Props) {
+export function ShoppingListItem({ name, isCompleted }: Props) {
const handleDelete = () => {
Alert.alert(
`Are you sure you want to delete ${name}?`,
@@ -22,11 +23,26 @@ export function ShoppingListItem({ name }: Props) {
};

return (
- <View style={styles.itemContainer}>
- <Text style={styles.itemText}>{name}</Text>
+ <View
+ style={[
+ styles.itemContainer,
+ isCompleted ? styles.completedContainer : undefined,
+ ]}
+ >
+ <Text
+ style={[
+ styles.itemText,
+ isCompleted ? styles.completedText : undefined,
+ ]}
+ >
+ {name}
+ </Text>
<TouchableOpacity
onPress={handleDelete}
- style={styles.button}
+ style={[
+ styles.button,
+ isCompleted ? styles.completedButton : undefined,
+ ]}
activeOpacity={0.8}
>
<Text style={styles.buttonText}>Delete</Text>
@@ -60,4 +76,16 @@ const styles = StyleSheet.create({
textTransform: "uppercase",
letterSpacing: 1,
},
+ completedContainer: {
+ backgroundColor: theme.colorLightGrey,
+ borderBottomColor: theme.colorLightGrey,
+ },
+ completedText: {
+ color: theme.colorGrey,
+ textDecorationLine: "line-through",
+ textDecorationColor: theme.colorGrey,
+ },
+ completedButton: {
+ backgroundColor: theme.colorGrey,
+ },
});

And update App.tsx to render multiple of these shopping list items:

Update: App.tsx
@@ -6,8 +6,8 @@ export default function App() {
return (
<View style={styles.container}>
<ShoppingListItem name="Coffee" />
- <ShoppingListItem name="Tea" />
- <ShoppingListItem name="Milk" />
+ <ShoppingListItem name="Tea" isCompleted />
+ <ShoppingListItem name="Milk" isCompleted />
</View>
);
}

Checkpoint

AndroidiOS