React Native Show Message for empty FlatList Example

Nov 17, 2022 . Admin

Today, I will let you know an example of how to show a message when flat list is empty. This article will give you a simple example of react native show message for an empty flat list example. This article will give you a simple example of show error message when flat list is empty in react native. if you have a question about how to show a message when the flat list is empty then I will give a simple example with a solution. Let's get started with how to show a message when flat list is empty react native.

In this example, When the data source of your FlatList component goes empty, then the user should make 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.

Step 1: Download Project

In the first step run the following command to create a project.

expo init ExampleApp
Step 2: App.js

In this step, You will open the App.js file and put the code.

import React, {useState, useEffect} from 'react';
import {View, Text, StyleSheet, FlatList, Button, StatusBar} from 'react-native';

const App = () => {
  const [data, setData] = useState('');

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => response.json())
      .then((json) => setData(json));
  }, []);

  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="red" />
      <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',
    marginTop:35
  },
  buttonView: {
    flexDirection: 'row',
  },
  titleStyle: {
    color: 'black',
  },
});

export default App;
Step 3: Run Project

In the last step run your project using the below command.

expo start

You can QR code scan in Expo Go Application on mobile.

Output:

It will help you...

#React Native