简体   繁体   中英

React Native Horizontal FlatList Wrap to New Line

I want to wrap the individual item in my FlatList and render them in a new line. Currently, the items don't wrap around and render outside of the screen. Please see the image and code below. How can I fix this? Thanks! 在此处输入图像描述

import { View, Text, StyleSheet, FlatList } from "react-native";
import CategoryListItem from "./CategoryListItem";

const categories = [
  "Apparels & Fashion",
  "Accessories",
  "Electronics",
  "Food",
  "Books",
  "Courses",
  "Music",
  "Misc.",
];

const CategoryList = () => {
  return (
    <View style={styles.container}>
      <FlatList
        data={categories}
        renderItem={({ item }) => <CategoryListItem category={item} />}
        style={styles.list}
        horizontal={true}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flexShrink: 1,

    margin: 5,
    padding: 5,
    borderRadius: 10,
    backgroundColor: "#fffffa",

    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,

    elevation: 5,
  },
  list: {
    padding: 10,
    flexDirection: "column",
  },
});

export default CategoryList;

If you applied some styling to the FlatList's contentContainerStyle prop you can get the desired effect ( link ):

import { View, Text, StyleSheet, FlatList } from 'react-native';
import CategoryListItem from './CategoryListItem';

const categories = [
  'Apparels & Fashion',
  'Accessories',
  'Electronics',
  'Food',
  'Books',
  'Courses',
  'Music',
  'Misc.',
];

const CategoryList = () => {
  return (
    <View style={styles.container}>
      <FlatList
        data={categories}
        renderItem={({ item }) => <CategoryListItem category={item} />}
        style={styles.list}
        contentContainerStyle={styles.listContents}
        horizontal={true}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flexShrink: 1,
    margin: 5,
    padding: 5,
    borderRadius: 10,
    backgroundColor: '#fffffa',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
  list: {
    padding: 10,
    flexDirection: 'column',
  },
  listContents: {
    flexDirection: 'row',
    width: '100%',
    flexWrap: 'wrap',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default CategoryList;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM