Spacing before and after a horizontal FlatList (React Native)

Saad picture Saad · Nov 9, 2018 · Viewed 10.4k times · Source

I'm trying to create a horizontal FlatList that has some spacing around it. I was able to get the beginning spacing correct with paddingLeft on the list, but paddingRight on the list doesn't seem to put any space after it (if I scroll all the way to the end, the last item is pressed right against the border).

Here is a Snack so that you can run and try this out live: https://snack.expo.io/@saadq/aW50cm

And here is my code:

import * as React from 'react';
import { Text, View, FlatList, StyleSheet } from 'react-native';

const data = [{ key: 1 }, { key: 2 }, { key: 3 }, { key: 4 }];

class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <FlatList
          style={styles.flatList}
          horizontal
          data={data}
          renderItem={() => (
            <View style={styles.box}>
              <Text>Box</Text>
            </View>
          )}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  flatList: {
    marginTop: 100,
    paddingLeft: 15,
    paddingRight: 15, // THIS DOESN'T SEEM TO BE WORKING
    // marginRight: 15   I can't use marginRight because it cuts off the box with whitespace
  },
  box: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    height: 50,
    width: 100,
    borderWidth: 1,
    borderColor: 'black',
    paddingHorizontal: 15,
    marginRight: 15,
  },
});

export default App;

Using marginRight instead of paddingRight does seem to give the expected spacing result, however it causes a different issue where that whitespace is ALWAYS there and cuts off the items when scrolling. Any help would be appreciated!

Answer

Saad picture Saad · Nov 9, 2018

Seems like I was able to fix it by using a contentContainerStyle prop on the FlatList instead of passing it a style prop directly.