Reputation: 578
I have an array of objects in React Native. What is the simplest way to map them two on a row like in the following picture:
https://i.sstatic.net/VGWTr.png
I have a function that converts an array into an array of arrays of 2 elements:
{/* Example input: [0, 1, 2, 3, 4, 5, 6, 7] */}
{/* Example output: [ [0, 1] , [2, 3] , [4, 5] , [6, 7] ] */}
then simply map each element into a View that contains two other View elements, but seems way too overkill.
Is there a simpler method?
Upvotes: 0
Views: 2505
Reputation: 10651
Instead of map, the Better way is to Use FlatList
with propnumColumns={2}
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={item => item.id}
numColumns={2}
/>
Full Example:
Working Demo: Expo Snack
Output:
Source Code:
import * as React from 'react';
import { Text, View, StyleSheet, FlatList } from 'react-native';
import Constants from 'expo-constants';
const list = [0, 1, 2, 3, 4, 5, 6, 7];
export default function App() {
return (
<View style={styles.container}>
<FlatList
data={list}
numColumns={2}
keyExtractor={(item)=> item}
renderItem={({ item }) => (
<View style={styles.card}>
<Text style={styles.text}>{item}</Text>
</View>
)}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
card: {
height: 100,
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#212121',
boxShadow: "10px 10px 0px -5px rgba(209,25,209,1)",
margin: 5,
borderRadius: 10,
},
text: {
fontSize: 40,
fontWeight: '600',
color: 'white',
},
});
Upvotes: 2
Reputation: 306
yes, there is a simpler way. You could set width 50% to each element and to the parent set flexDirection: 'row' and flexWrap: 'wrap'
Upvotes: 1