How to display all products with the same category in a horizontal flatlist or sectionlist React Native

Viewed 31

I want to display all products with the same category in a horizontal flatlist with category name as title

do I need to group my fetched data by category, if so how to do it? which is better for this scenario flatlist or sectionlist.



const HomeScreen = ({ navigation }) => {
  const [products, setProducts] = useState<any[]>([]);
  const [categories, setCategory] = useState<any[]>([]);

  

  useEffect(() => {
    fetch("https://dummyjson.com/products")
      .then((response) => response.json())
      .then(({ products }) => {
        setProducts(products);
      })

      .catch((error) => console.log(error));
  });
  return products.length > 0 ? (
    <View
      style={{
        backgroundColor: COLORS.backgroundLight,
        marginTop: 20,
      }}
    >
      <View
        style={{
          width: "100%",
          flexDirection: "row",
          justifyContent: "space-between",
          padding: 16,
        }}
      >
        <TouchableOpacity onPress={() => navigation.openDrawer()}>
          <MaterialIcons name="menu" size={30} color="black" />
        </TouchableOpacity>
        <TouchableOpacity onPress={() => navigation.navigate("CartScreen")}>
          <Feather name="shopping-cart" size={30} color="black" />
        </TouchableOpacity>
      </View>
      <FlatList
        data={products}
        keyExtractor={(products) => products.id.toString()}
        numColumns={2}
        renderItem={({ item }) => (
          <ProductCard
            title={item.title}
            price={item.price}
            image={item.images[0]}
            onPress={() => navigation.navigate("ProductDetails", item)}
          />
        )}
      />
    </View>
  ) : (
    <View
      style={{
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <ActivityIndicator size="large" />
    </View>
  );
};

export default HomeScreen;

I have been stuck in this for ages please help

1 Answers

I ran into same problems before. I solved with SectionList instead of Flatlist. You need to change your data structures into something like this.

const DATA = [
  {
    title: "First Category",
    data: [...all items of that category]
  },
  {
    title: "Second Category",
    data: [...all items of that category]
  },
  ...
]
Related