Dynamic Quantity Counters in a List
Screen is created using these React Native Core Components: <SafeAreaView />, <View />, <Text />, <TouchableOpacity />
import React from 'react';
import {
StyleSheet,
SafeAreaView,
View,
Text,
TouchableOpacity,
} from 'react-native';
const items = [
{
id: '1923',
label: 'T-shirt',
description: 'Classic cotton tee with a relaxed fit.',
},
{
id: '1924',
label: 'Jeans',
description: 'Slim-fit denim jeans with a distressed finish.',
},
{
id: '1925',
label: 'Sneakers',
description: 'Athletic shoes with cushioned soles for all-day comfort.',
},
{
id: '1926',
label: 'Dress',
description: 'Elegant midi dress with a floral print and a v-neckline.',
},
{
id: '1927',
label: 'Hoodie',
description:
'Cozy sweatshirt with a kangaroo pocket and a drawstring hood.',
},
];
export default function Example() {
const [value, setValue] = React.useState({});
return (
<SafeAreaView style={{ flex: 1, backgroundColor: '#fff' }}>
<View style={styles.container}>
{items.map(({ id, label, description }) => {
return (
<View key={id} style={styles.row}>
<View style={styles.rowBody}>
<Text style={styles.rowTitle}>{label}</Text>
<Text style={styles.rowSubtitle}>{description}</Text>
</View>
<View style={styles.counter}>
<TouchableOpacity
disabled={(value[id] ?? 0) <= 0}
onPress={() => {
setValue({
...value,
[id]: Math.max((value[id] ?? 0) - 1, 0),
});
}}
style={styles.counterAction}>
<Text style={styles.counterActionText}>-</Text>
</TouchableOpacity>
<Text style={styles.counterValue}>{value[id] ?? 0}</Text>
<TouchableOpacity
onPress={() => {
setValue({ ...value, [id]: (value[id] ?? 0) + 1 });
}}
style={styles.counterAction}>
<Text style={styles.counterActionText}>+</Text>
</TouchableOpacity>
</View>
</View>
);
})}
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
padding: 24,
flexGrow: 1,
flexShrink: 1,
flexBasis: 0,
},
/** Row */
row: {
flexDirection: 'row',
alignItems: 'flex-start',
justifyContent: 'space-between',
marginBottom: 16,
},
rowBody: {
flexGrow: 1,
flexShrink: 1,
flexBasis: 0,
paddingRight: 12,
},
rowTitle: {
fontSize: 19,
fontWeight: '600',
color: '#1d1d1d',
marginBottom: 4,
},
rowSubtitle: {
fontSize: 14,
lineHeight: 18,
color: '#68676a',
},
/** Counter */
counter: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
alignSelf: 'center',
borderWidth: 1,
borderColor: '#ececec',
borderStyle: 'solid',
borderRadius: 9999,
},
counterAction: {
width: 34,
height: 34,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
counterActionText: {
fontSize: 20,
lineHeight: 20,
fontWeight: '500',
color: '#000',
},
counterValue: {
minWidth: 28,
fontSize: 14,
fontWeight: 'bold',
color: '#000',
textAlign: 'center',
paddingHorizontal: 8,
},
});