FlatList in React Native
1) FlatList Example in React Native
FlatList:- We use FlatList to show a list of items from JSON or whatever See example data below
import React from 'react';
import { View, StyleSheet, Text, FlatList } from 'react-native';
const DATA = [
{
key: 1,
item: 'Item1',
},
{
key: 2,
item: 'Item2',
},
{
key: 3,
item: 'Item3',
},
{
key: 4,
item: 'Item4',
},
{
key: 5,
item: 'Item5',
},
]
function getColor() {
var ColorCode = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
return ColorCode;
}
export default function FlatListExample() {
const renderItem = ({item}) => {
return(
<View style={[styles.view1, { backgroundColor: getColor() }]} key={item.key}>
<Text style={styles.text}>{item.item}</Text>
</View>
)
}
return (
<View style={styles.conatainer}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={(item) => item.key}
/>
</View>
);
}
const styles = StyleSheet.create({
conatainer: {
flex:1,
backgroundColor: 'red'
},
view1: {
height:200,
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 30,
fontWeight: 'bold',
color: 'white'
}
})
OUTPUT:-
2) Display items In multiple columns in FlatList React Native
import React from 'react';
import { View, StyleSheet, Text, FlatList} from 'react-native';
const DATA = [
{
key: 1,
item: 'Item1',
},
{
key: 2,
item: 'Item2',
},
{
key: 3,
item: 'Item3',
},
{
key: 4,
item: 'Item4',
},
{
key: 5,
item: 'Item5',
},
{
key: 6,
item: 'Item6',
},
{
key: 7,
item: 'Item7',
},
{
key: 8,
item: 'Item8',
},
{
key: 9,
item: 'Item9',
},
{
key: 10,
item: 'Item10',
},
]
function getColor() {
var ColorCode = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
return ColorCode;
}
export default function FlatListExample() {
const renderItem = ({item}) => {
return(
<View style={[styles.view1, { backgroundColor: getColor()}]} key={item.key}>
<Text style={styles.text}>{item.item}</Text>
</View>
)
}
return (
<View style={styles.conatainer}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={(item) => item.key}
numColumns={2}
/>
</View>
);
}
const styles = StyleSheet.create({
conatainer: {
flex:1,
},
view1: {
height:100,
alignItems: 'center',
justifyContent: 'center',
width:'50%'
},
text: {
fontSize: 30,
fontWeight: 'bold',
color: 'white'
}
})
OUTPUT:-
Comments
Post a Comment