Home > database >  React Native: How to get horizontal FlatList to span the full width?
React Native: How to get horizontal FlatList to span the full width?

Time:12-27

I have a set of boxes inside a flatlist. How can I get the boxes to stretch to fix the width of the FlatList?

Easier to look at it on this Expo Snack

<FlatList
  data={DATA}
  horizontal={true}
  contentContainerStyle={{ flex: 1, justifyContent: 'center', alignItems: "center" }}
  style={{ backgroundColor: 'skyblue', width: "100%" }}
  renderItem={({ item, idx }) => (
    <View
      key={'flatlist'   idx}
      style={{ backgroundColor: 'powderblue', padding: 10, margin: 5, flex:1, width: "100%" }}>
      <Text>{item.id}</Text>
    </View>
  )}
  keyExtractor={(item) => item.id}
/>

CodePudding user response:

Couldn't properly understand what you want, but try this code by taking the Dimension width, rather than giving 100%


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

const {width} = Dimensions.get("window");

const DATA = [
  {
    id: '1',
    title: 'First Item',
  },
  {
    id: '2',
    title: 'Second Item',
  },
  {
    id: '3',
    title: 'Third Item',
  },
  {
    id: '4',
    title: 'Forth Item',
  },
];

export default function App() {
  return (
    <View
      style={{
        flex: 1,
        justifyContent: 'center',
        paddingTop: Constants.statusBarHeight,
        backgroundColor: '#ecf0f1',
        padding: 8,
      }}>
      <View style={{ height: 600}}>
        <Text>How do you get the boxes to span the width?</Text>
        <FlatList
          data={DATA}
          horizontal={true}
          style={{ backgroundColor: 'skyblue', width: "100%" }}   
          renderItem={({ item, idx }) => (
            <View
              key={'flatlist'   idx}
              style={{ backgroundColor: 'powderblue', padding: 10, margin: 5, flex:1, width: width }}>
              <Text>{item.id}</Text>
            </View>
          )}
          keyExtractor={(item) => item.id}
        />
      </View>
    </View>
  );
}

CodePudding user response:

I figured it out. You have to make the following adjustments. The key being that alignItems can become stretch

<FlatList
    numColumns={4}
    horizontal={false}
    contentContainerStyle={{alignItems: "stretch"}}
/>

The full component

<FlatList
    data={DATA}
    horizontal={false}
    numColumns={4}
    contentContainerStyle={{ flex: 1, justifyContent: 'center', alignItems: "stretch" }}
    style={{ backgroundColor: 'skyblue', width: "100%" }}
    renderItem={({ item, idx }) => (
    <View
        key={'flatlist'   idx}
        style={{ backgroundColor: 'powderblue', padding: 10, margin: 5, flex:1, width: "100%" }}>
        <Text>{item.id}</Text>
    </View>
    )}
    keyExtractor={(item) => item.id}
/>
  • Related