I’m learning to use react-native by creating an application, so I’m creating a scrollable homepage and inside it 10 rectangle with different names. If I understand correctly, you need to use flatlist to manage the scrolling of these rectangles, but I already have a scrollview within the same page. I have something like this:
<ScrollView>
<Image/>
<Text/>
<RectangleComponents/>
</ScrollView>
Inside RectanglesComponent is the code that creates the 10 rectangles. I’m currently using a ScrollView here too because I couldn’t use FlatList inside a ScrollView. Example of RectanglesComponent:
return (
<SafeAreaView style={styles.container}>
{Array.from(Array(10).keys()).map(i => (
<SafeAreaView key={i} style={styles.rectangle}/>
</SafeAreaView>
);
In this case i need to use FlatList or ScrollView is good?
2
Answers
In this situation, if you aim for a homepage where you can scroll through a list of rectangles, it’s best to use FlatList instead of ScrollView, especially for handling a large number of items effectively. Nonetheless, given your existing ScrollView containing all the content, you can still attain your desired layout by placing a FlatList within the ScrollView.
import React from ‘react’;
import {
RectangleComponent represents each rectangle item in your list. It’s a functional component that takes an index as a prop and renders a rectangle with the corresponding index.
HomeScreen is your main component. It contains your existing content (image, text) within the ScrollView, and then a FlatList for rendering the rectangles.
renderRectangle is the function used by FlatList to render each item. It passes the index to RectangleComponent.
keyExtractor is used to generate keys for items in the FlatList.
By nesting the FlatList inside the ScrollView, you can maintain your existing scrollable layout while efficiently rendering a large number of rectangle items using FlatList.
Update
Feedback: I’m trying now, but i get this error: "VirtualizedLists should never be nested inside plain ScrollViews with the same orientation because it can break windowing and other functionality – use another VirtualizedList-backed container instead." –
frak01
The error you’re encountering indicates that nesting a FlatList (which is a virtualized list component) inside a ScrollView (another scrolling container) is not recommended because it can lead to issues with scrolling behavior and performance. To address this error, you need to remove the outer ScrollView and use only the FlatList as the main scrolling container. I will update the code –
Anthony Heremans
You can use
Note: RN should be greater then 56.0
Example:
https://snack.expo.dev/@msbot01/blessed-orange-yogurt