FlatList component in react native !

flatlist in react native !

In React Native, you can use the FlatList component to display a scrollable list of items in your app. Here's an example of how to use FlatList to display a simple flat list:
Code :-

import React, { useState } from 'react';
import { FlatList, Text, View } from 'react-native';
const data = [
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' },
  { id: 3, name: 'Item 3' },
  { id: 4, name: 'Item 4' },
  { id: 5, name: 'Item 5' },
];
const FlatListExample = () => {
  const renderItem = ({ item }) => (
    <View style={{ padding: 10 }}>
      <Text>{item.name}</Text>
    </View>
  );
  return (
    <FlatList
      data={data}
      renderItem={renderItem}
      keyExtractor={(item) => item.id.toString()}
    />
  );
};
export default FlatListExample;

In this example, we define an array of data with each item having an id and name property. We then define a renderItem function that takes an item from the data array and renders it as a View with a Text component displaying the name property.

We pass the data array, renderItem function, and a keyExtractor function (which extracts the id property from each item and returns it as a string) to the FlatList component as props.
When the component is rendered, it displays a scrollable list of items with each item rendered using the renderItem function.

To make a FlatList component behave like a carousel in React Native, you can use the snapToInterval and horizontal props to control the scrolling behavior. Here's an example

import React from 'react';
import { View, Text, FlatList } from 'react-native';
const data = [
  { id: 1, title: 'Item 1' },
  { id: 2, title: 'Item 2' },
  { id: 3, title: 'Item 3' },
  { id: 4, title: 'Item 4' },
  { id: 5, title: 'Item 5' },
];
const Carousel = () => {
  const renderItem = ({ item }) => (
    <View style={{ width: 200, height: 200, backgroundColor: 'white', margin: 10 }}>
      <Text>{item.title}</Text>
    </View>
  );
  return (
    <FlatList
      data={data}
      renderItem={renderItem}
      keyExtractor={(item) => item.id.toString()}
      horizontal
      snapToInterval={210}
      showsHorizontalScrollIndicator={false}
    />
  );
};
export default Carousel;

0 Comments