Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grid view in React Native Flatlist

How can I achieve such a view like this in react native in a FlatList component?

Usually in web It's easy with css grid but I could not a way to do this in react native.

enter image description here

like image 828
Ozzie Avatar asked Jan 25 '23 22:01

Ozzie


1 Answers

If you want to render an n by n grid, you could utilize FlatList's numColumns property. Then you could just pass the data into the FlatList's data property to specify how to render each cell in the grid by passing a function in the renderItem property.

A rough example would look like this:

import { FlatList } from "react-native";

<FlatList 
  data={myData}
  numColumns={3}
  renderItem={({ item }) => <MyCellComponent cellData={item} />}
/>

However, your question is a bit different as you want to render an uneven grid. You could divide the grid into two separate components, ComponentA and ComponentB, and render them inside of a ScrollView as such.

enter image description here

A rough code example would look like this:

import { ScrollView } from "react-native";

<ScrollView>
  <ComponentA />
  <ComponentB />
  <ComponentA />
</ScrollView>

Although, if you really want to use a FlatList, then you could create a 3rd component, ComponentC, which would basically wrap the previous example like so:

import { View } from "react-native";

function ComponentC() {
  return (
    <View>
      <ComponentA />
      <ComponentB />
      <ComponentA />
    </View>
  );
}

and then render that inside of a FlatList:

<FlatList 
  data={myData}
  renderItem={({ item }) => (<ComponentC data={item} />)}
/>
like image 97
driouxg Avatar answered Feb 05 '23 18:02

driouxg