Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing list empty message at the center of the screen in a FlatList using ListHeaderComponent

I am using React-Native version 0.43.0 which does not support ListEmptyComponent of FlatList. Hence I am using ListHeaderComponent to render a view when the list is empty,

import React, { Component } from 'react'; import { Text, View, StyleSheet,FlatList } from 'react-native';  class App extends Component {   constructor(props) {     super(props);     this.state = {       listData: []     }   }   render() {     return (       <View style={styles.container}>         <FlatList           renderItem={() => null}           data={this.state.listData}           ListHeaderComponent={() => (!this.state.listData.length?              <Text style={styles.emptyMessageStyle}>The list is empty</Text>               : null)           }         />       </View>     );   } }  const styles = StyleSheet.create({   container: {     flex:1   },   emptyMessageStyle: {     textAlign: 'center',     //My current hack to center it vertically     //Which does not work as expected     marginTop: '50%',    } }); 

enter image description here

As you can see from the image the text is not centered vertically

Any idea how to center it vertically in a FlatList?

I have already tried applying justifyContent, alignItems etc but no use.

This is a link to the snack.expo - https://snack.expo.io/S16dDifZf

like image 475
Ravi Raj Avatar asked Dec 04 '17 11:12

Ravi Raj


People also ask

What is key extractor in FlatList?

keyExtractor ​ (item: object, index: number) => string; Used to extract a unique key for a given item at the specified index. Key is used for caching and as the react key to track item re-ordering. The default extractor checks item. key , then item.id , and then falls back to using the index, like React does.


Video Answer


1 Answers

Hope this will help you

<FlatList     contentContainerStyle={{ flexGrow: 1 }}     disableVirtualization={false}     data={this.state.data}     renderItem={this.renderItem}     ListEmptyComponent={this.renderEmptyContainer()}       />     }   /> 

Place your UI in the renderEmptyContainer() method and boom, Empty container will show up whenever your list is empty

like image 170
Aakash Daga Avatar answered Sep 22 '22 01:09

Aakash Daga