Last Updated on December 13, 2020.
A FlatList is the most suitable component in case of showing the same sort of dynamic data in your react native mobile application. In this blog post, I will explain how to show a text message through FlatList when it is empty.
When the data source of your FlatList component goes empty, then the user should made know about the reason behind it. You can use ListEmptyComponent prop of FlatList for this purpose. ListEmptyComponent accepts a react component class or a rendered element or a render function.
In the following react native flatlist empty component example, I am loading data to the FlatList using an API. When the button above flatlist is pressed the data is made empty and you can see the message ‘oops! There’s no data here’!.
Class based component
import React, { Component } from 'react';
import { View, Text, StyleSheet, FlatList, Button } from 'react-native';
class MyClass extends Component {
constructor(props){
super(props);
this.state={
data: '',
}
}
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(json => this.setState({
data: json
}))
}
emptyComponent= () => {
return(
<View style={{flex: 1}}>
<Text style={styles.titleStyle}>oops! There's no data here!</Text>
</View>);
}
clearData= () => {
this.setState({
data:''
})
}
render() {
return (
<View style={styles.container}>
<Button
onPress={()=> this.clearData()}
title="Clear Data"
color="#841584"/>
<FlatList
data={this.state.data}
ListEmptyComponent={this.emptyComponent}
renderItem={({item}) => <Text>{item.title}</Text>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
},
buttonView: {
flexDirection: 'row'
},
titleStyle: {
color: 'black'
}
});
export default MyClass;
Function based component
import React, {useState, useEffect} from 'react';
import {View, Text, StyleSheet, FlatList, Button} from 'react-native';
const App = () => {
const [data, setData] = useState('');
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((json) => setData(json));
console.log('test');
}, []);
const emptyComponent = () => {
return (
<View style={{flex: 1}}>
<Text style={styles.titleStyle}>oops! There's no data here!</Text>
</View>
);
};
const clearData = () => {
setData('');
};
return (
<View style={styles.container}>
<Button onPress={() => clearData()} title="Clear Data" color="#841584" />
<FlatList
data={data}
ListEmptyComponent={emptyComponent}
renderItem={({item}) => <Text>{item.title}</Text>}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
},
buttonView: {
flexDirection: 'row',
},
titleStyle: {
color: 'black',
},
});
export default App;
The output of the react-native example is as given below:
