erikmay
erikmay

Reputation: 33

How to display different content in a FlatList

I'm currently stuck on a problem that I don't know how to solve properly.

I want to create a feed for the start page of my app. The feed should be infinitely scrollable and as resource-efficient as possible. Of course, this can all be done with the FlatList Component, but I don't know how to display different types of components in the FlatList.

Here is a picture with an example of how I mean different types of components:

Example of complex layout

So the layout has to be very flexible and I don't know how to do that with a FlatList. I have already thought about conditional rendering, but again I am missing a way of making it work correctly.

Have any of you ever solved such a problem? I would be grateful for any suggestions!

Upvotes: 3

Views: 1352

Answers (1)

Luís C Meireles
Luís C Meireles

Reputation: 469

You can create a component that returns your different types of content dynamically, for example:

const mock = [
  {
    type: 'feed_1',
    title: 'Lorem',
    feed: [],
  },
  {
    type: 'feed_2',
    title: 'Ipsum',
    feed: [],
  }
]

function App() {
  return (
    <FlatList
      data={mock}
      renderItem={(item) => <Dynamic item={item} />}
    />
  );
}

const Dynamic = memo(({item}) => { 
  switch (item.type) {
    case 'feed_1':
      return <ComponentForFeed1 data={item} />
    case 'feed_2':
      return <ComponentForFeed2 data={item} />

    default:
      return null;
  }
})

You should also use memo on your "Dynamic" component to prevent unnecessary renders, don't take the above code to literal, it's just a draft of what you can do to change the render dynamically.

Also you can get similar characteristics of your sections and put them on the Dynamic component, this way you just change the actual content.

Upvotes: 3

Related Questions