Search code examples
react-nativereact-native-flatlist

Separator style for header and body in FlatList


Currently, I'm having a problem with FlatList. I have a component to render a list book. By design, the header's width is the width of the screen and the body will be padding left and right 10px.

So I used contentContainerStyle={{paddingHorizontal: 10}}. But The result is that the header and body are 10px padding left and right.

Please suggest a way to resolve it. Sorry for my bad English!!

Update: I'm so sorry for not describing my problem thoroughly.

In main.tsx

...
public render() {
  return (
    <FlatList
      key...
      data={..}
      renderItem={this.renderItems}
      ListHeaderComponent={this.renderHeader}
      contentContainerStyle={styles.contentStyle}
    />
  );
}

private renderHeader = () => {
  return (
    <View style={style.header}
      //TODO something ...
    </View>
  );
}

private renderItems: ListRenderItem<IBook> = ({ item: {bookId} }) => bookId ?
  (
    <BookGridCell
      title={...}
      image={...}
      //TODO more..
    />
  ) : <View style={styles.emptyBox} /> 
}

At renderItems, I called a component BookGridCell. In this component, the design of a book is set up. So if I directly add style inside renderItems, each book will have a left and right margin of 10px, not the entire body.

When use contentContainerStyle with contenContainerStyle

When directly add style inside renderItems with not use contentContainerStyle


Solution

    1. Give a style to your body.

      style={styles.bodyContainer}
      

    and then inside StyleSheet add property.

        const styles = StyleSheet.create({
        bodyContainer: {
          paddingHorizontal: 10    
          },
    

    This is the correct way or

    1. you can directly add padding inside your View.

      style={{ paddingHorizontal: 10 }}