Skip to content

Instantly share code, notes, and snippets.

@lucasferreira
Created June 21, 2019 12:11
Show Gist options
  • Save lucasferreira/5da368661a8c59f0172088419b308737 to your computer and use it in GitHub Desktop.
Save lucasferreira/5da368661a8c59f0172088419b308737 to your computer and use it in GitHub Desktop.
React Native FlatList Grid
// code by @spencercarli
import React from 'react';
import { StyleSheet, Text, View, FlatList, Dimensions } from 'react-native';
const data = [
{ key: 'A' }, { key: 'B' }, { key: 'C' }, { key: 'D' }, { key: 'E' }, { key: 'F' }, { key: 'G' }, { key: 'H' }, { key: 'I' }, { key: 'J' },
];
const formatData = (data, numColumns) => {
const numberOfFullRows = Math.floor(data.length / numColumns);
let numberOfElementsLastRow = data.length - (numberOfFullRows * numColumns);
while (numberOfElementsLastRow !== numColumns && numberOfElementsLastRow !== 0) {
data.push({ key: `blank-${numberOfElementsLastRow}`, empty: true });
numberOfElementsLastRow++;
}
return data;
};
const numColumns = 3;
export default class App extends React.Component {
renderItem = ({ item, index }) => {
if (item.empty === true) {
return <View style={[styles.item, styles.itemInvisible]} />;
}
return (
<View
style={styles.item}
>
<Text style={styles.itemText}>{item.key}</Text>
</View>
);
};
render() {
return (
<FlatList
data={formatData(data, numColumns)}
style={styles.container}
renderItem={this.renderItem}
numColumns={numColumns}
/>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginVertical: 20,
},
item: {
backgroundColor: '#4D243D',
alignItems: 'center',
justifyContent: 'center',
flex: 1,
margin: 1,
height: Dimensions.get('window').width / numColumns, // approximate a square
},
itemInvisible: {
backgroundColor: 'transparent',
},
itemText: {
color: '#fff',
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment