skip to Main Content

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


  1. 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 {

     SafeAreaView, ScrollView, FlatList, View, Text, StyleSheet } from 'react-native';
    
    const RectangleComponent = ({ index }) => {
      return (
        <View key={index} style={styles.rectangle}>
          <Text>{`Rectangle ${index + 1}`}</Text>
        </View>
      );
    };
    
    const HomeScreen = () => {
      const renderRectangle = ({ index }) => <RectangleComponent index={index} />;
    
      return (
        <SafeAreaView style={styles.container}>
          <ScrollView>
            {/* Your existing content */}
            <Image />
            <Text>Some Text</Text>
    
            {/* FlatList for rectangles */}
            <FlatList
              data={Array.from(Array(10).keys())}
              renderItem={renderRectangle}
              keyExtractor={(item, index) => index.toString()}
            />
          </ScrollView>
        </SafeAreaView>
      );
    };
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
      },
      rectangle: {
        height: 100,
        backgroundColor: 'lightblue',
        marginVertical: 10,
        justifyContent: 'center',
        alignItems: 'center',
      },
    });
    
    export default HomeScreen;
    

    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

    import React from 'react';
    import { FlatList, SafeAreaView, StyleSheet, Text } from 'react-native';
    
    const data = Array.from(Array(10).keys()).map(i => ({ key: String(i), name: `Rectangle ${i}` }));
    
    const RectanglesComponent = () => {
      const renderItem = ({ item }) => (
        <SafeAreaView key={item.key} style={styles.rectangle}>
          <Text>{item.name}</Text>
        </SafeAreaView>
      );
    
      return (
        <FlatList
          data={data}
          renderItem={renderItem}
          keyExtractor={item => item.key}
        />
      );
    };
    
    const styles = StyleSheet.create({
      rectangle: {
        // Your rectangle styles here
        width: 100,
        height: 50,
        backgroundColor: 'red',
        marginVertical: 10,
        alignItems: 'center',
        justifyContent: 'center',
      },
    });
    
    export default RectanglesComponent;
    
    Login or Signup to reply.
  2. You can use

    <ScrollView nestedScrollEnabled = {true}>
     ......
      <ScrollView nestedScrollEnabled = {true}>
        .....
      </ScrollView>
    </ScrollView>
    

    Note: RN should be greater then 56.0

    Example:
    https://snack.expo.dev/@msbot01/blessed-orange-yogurt

    import {View, Text, SafeAreaView, StyleSheet, ScrollView, Image } from 'react-native';
    
    // You can import supported modules from npm
    import { Card } from 'react-native-paper';
    
    // or any files within the Snack
    import AssetExample from './components/AssetExample';
    
    export default function App() {
    
      const rectBox=()=>{
        var tempArray = [];
    
        for(var i=0; i<10;i++){
          let eachElement = <View style={{height:150,width:'100%',backgroundColor:'green', marginTop:20}}>
              <Text>{i}</Text>
          </View>
          tempArray.push(eachElement)
        }
    
        return tempArray;
      }
    
      const rectBox02=()=>{
        var tempArray = [];
    
        for(var i=0; i<10;i++){
          let eachElement = <View style={{height:150,width:'100%',backgroundColor:'yellow', marginTop:20}}>
              <Text>{i}</Text>
          </View>
          tempArray.push(eachElement)
        }
    
        return tempArray;
      }
    
      return (
        <SafeAreaView style={styles.container}>
         <ScrollView nestedScrollEnabled = {true}>
            <Image
            style={styles.tinyLogo}
            source={{
              uri: 'https://reactnative.dev/img/tiny_logo.png',
            }}
          />
          
          <ScrollView nestedScrollEnabled = {true} style={{height:300}}>
            {rectBox()}
          </ScrollView>
    
          <ScrollView nestedScrollEnabled = {true} style={{height:300}}>
            {rectBox02()}
          </ScrollView>
    
         </ScrollView>
        </SafeAreaView>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        backgroundColor: '#ecf0f1',
        padding: 8,
      },
      tinyLogo: {
        width: 50,
        height: 50,
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search