Ask Your Question
1

How can a FlatList with multiple rows be made horizontal using React Native?

asked 2021-04-25 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-04-25 01:00:00 +0000

devzero gravatar image

One way to make a FlatList with multiple rows horizontal in React Native is by using the flexbox layout.

  1. Set the flexDirection of the container view to 'row'. This will make the items inside the container to be in a horizontal position.

  2. Set the horizontal props of FlatList to true. This will make the FlatList itself to be scrolls horizontally.

  3. Set the renderItem function to render items horizontally. This can be done by wrapping the components in a horizontal ScrollView.

Here is a code example:

import React from 'react';
import { FlatList, ScrollView, Text, View } from 'react-native';

const DATA = [
  { title: 'Title 1', content: 'Content 1' },
  { title: 'Title 2', content: 'Content 2' },
  { title: 'Title 3', content: 'Content 3' },
  { title: 'Title 4', content: 'Content 4' },
  { title: 'Title 5', content: 'Content 5' },
];

const Item = ({ title, content }) => (
  <View style={{ width: 200, marginRight: 10, borderWidth: 1 }}>
    <Text style={{ fontSize: 24 }}>{title}</Text>
    <Text>{content}</Text>
  </View>
);

const App = () => {
  const renderItem = ({ item }) => (
    <ScrollView horizontal>
      <Item title={item.title} content={item.content} />
    </ScrollView>
  );

  return (
    <View style={{ flexDirection: 'row' }}>
      <FlatList
        data={DATA}
        renderItem={renderItem}
        keyExtractor={(item) => item.title}
        horizontal={true}
      />
    </View>
  );
};

export default App;

In this example, the FlatList is wrapped in a View with flexDirection set to 'row'. The Item component is wrapped in a ScrollView with horizontal set to true. This allows each row to be displayed horizontally. The width is also set to a fixed value to ensure that each item is the same size.

Note: depending on the number of items to display, it may be necessary to set a width for the FlatList container or use pagination to avoid an overflow in the view.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-04-25 11:00:00 +0000

Seen: 13 times

Last updated: Apr 25 '22