React Native allows children to evenly fill in the empty space available

I am facing an issue with a container that contains a nested scrollview component. Inside this scrollview container, I am iterating through data to display the children in 2 items per row and automatically fill any remaining empty space. However, currently, it is only filling up half of the parent container.

https://i.sstatic.net/HlKTKlKO.png

The goal is to evenly distribute the height of the 6 boxes displayed in the image and fill in the remaining space in the container.

// React Native Element

  return (
    <SafeAreaView style={[{ flex: 1 }]}>
      <ScrollView
        contentContainerStyle={surveyScreenStyles().cardsContainer}
      >
        <View
          style={[surveyScreenStyles().cardsContainer]}
        >
          {surveyData?.surveys?.map((surveyDetails, i) => (
            <Card
              key={`suvey-card-${i}`}
              mode='elevated'
              style={[surveyScreenStyles().cards]}
            >
              <Card.Title
                title={surveyDetails.name}
                titleVariant='titleLarge'
                subtitle={surveyDetails.summary}
                subtitleNumberOfLines={2}
              />
            </Card>
          ))}
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}
// css file
{
    cardsContainer: {
      backgroundColor: "#FFFFFF",
      justifyContent: 'space-evenly',
      flex: 1,
      flexWrap: 'wrap',
      flexDirection: 'row',
      padding: 5,
      gap: 10
    },
    cards: {
      backgroundColor: "#FFFFFF",
      borderRadius: 10,
      flexBasis: '45%',
      justifyContent: 'center',
      padding: 10,
    }
}

Answer №1

Incorporating a flatlist enables you to utilize the numColumns prop along with the columnWrapperStyle prop to create 2 columns with customized spacing styles. To ensure the items occupy the remaining height, employing the onLayout prop helps determine the height, then dividing it by 3 due to having 2 items per row:

import {
  View,
  StyleSheet,
  ScrollView,
  SafeAreaView,
  FlatList,
  Image,
} from 'react-native';
import { Text, Card } from 'react-native-paper';
import { useState } from 'react';
import ResizeableView from './ResizeableView';
import useData from '../hooks/useData';

const numColumns = 2;
const gap = 10;

export default function AssetExample() {
  const [surveyData] = useData();
  const [flatlistHeight, setFlatlistHeight] = useState(0);
  return (
    <SafeAreaView style={{ flex: 1 }}>
      {/* draggable component to demonstrate responsiveness */}
      <ResizeableView />
      <FlatList
        style={{ flex: 1 }}
        data={surveyData?.surveys}
        contentContainerStyle={styles.cardsContainer}
        renderItem={({ item: surveyDetails, index: i }) => {
          const height = flatlistHeight / (6 / numColumns) - gap
          return (
            <Card
              mode="elevated"
              style={[
                styles.cards,
                { height },
              ]}>
              <Card.Content>
                <Card.Title
                  title={surveyDetails.name}
                  titleVariant="titleLarge"
                  subtitle={surveyDetails.summary}
                  subtitleNumberOfLines={2}
                />
                <Image
                  source={{ uri: surveyDetails.thumbnail }}
                  style={{ width: height*.5,height:height*.5, alignSelf:'center' }}
                />
              </Card.Content>
            </Card>
          );
        }}
        keyExtractor={(item, i) => `suvey-card-${i}`}
        onLayout={({ nativeEvent }) =>
          setFlatlistHeight(nativeEvent.layout.height)
        }
        numColumns={numColumns}
        columnWrapperStyle={{ justifyContent: 'space-evenly' }}
        pagingEnabled
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  cardsContainer: {
    flexGrow: 1,
    padding: 5,
    gap,
  },
  cards: {
    backgroundColor: '#FFFFFF',
    borderRadius: 10,
    flexBasis: '45%',
    justifyContent: 'center',
    // borderWidth: 1,
  },
});

preview

Answer №2

It appears that the issue may lie with the flexWrap property causing some disruptions. The scroll view seems to be affecting its functionality in an unexpected way.

While this solution may not be as sleek as yours, it achieves the desired outcome:

    <ScrollView
      contentContainerStyle={{
        flex: 1,
        flexDirection: 'column',
        padding: 5,
        gap: 10,
      }}
    >
      <View style={{ flex: 1, flexDirection: 'row', gap: 10 }}>
        <View
          style={{
            backgroundColor: '#FFFFFF',
            borderRadius: 10,
            justifyContent: 'center',
            padding: 10,
            flex: 1,
          }}
        ></View>
        <View
          style={{
            backgroundColor: '#FFFFFF',
            borderRadius: 10,
            justifyContent: 'center',
            padding: 10,
            flex: 1,
          }}
        ></View>
      </View>
      <View style={{ flex: 1, flexDirection: 'row', gap: 10 }}>
        <View
          style={{
            backgroundColor: '#FFFFFF',
            borderRadius: 10,
            justifyContent: 'center',
            padding: 10,
            flex: 1,
          }}
        ></View>
        <View
          style={{
            backgroundColor: '#FFFFFF',
            borderRadius: 10,
            justifyContent: 'center',
            padding: 10,
            flex: 1,
          }}
        ></View>
      </View>
      <View style={{ flex: 1, flexDirection: 'row', gap: 10 }}>
        <View
          style={{
            backgroundColor: '#FFFFFF',
            borderRadius: 10,
            justifyContent: 'center',
            padding: 10,
            flex: 1,
          }}
        ></View>
        <View
          style={{
            backgroundColor: '#FFFFFF',
            borderRadius: 10,
            justifyContent: 'center',
            padding: 10,
            flex: 1,
          }}
        ></View>
      </View>
    </ScrollView>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to ensure a string of words in HTML/CSS wraps to the next line seamlessly?

As I work on creating my portfolio website using Bootstrap and custom CSS, I am running into an issue with the game titles breaking in the middle when displayed. Despite my limited proficiency in English, I tried searching for a solution without success. ...

What is the best way to retrieve the color of a WebElement when dealing with a complex CSS structure in Webdriver

I am currently trying to determine if the color of a specific page changes immediately after clicking on a button designed to alter the color of an element within that page. My goal is to extract the RGB value stated as rgb(183,168,168); in this particul ...

Elegant trinket

Recently, I attempted to showcase a flash file and an image using Fancybox. If you want to visualize what I am referring to, please refer to the screenshot below: Objectives: Automatically load Fancybox on page load with both the .swf file and the .jpg ...

Navigate to designated part of a website using HTML and CSS styling

Consider the following JavaScript code: //Scroll Down button $(window).scroll(function () { if ($(this).scrollDown() > 100) { $('.containerScroll').fadeIn('slow'); } else { $('.containerScroll').fadeOut('slow'); } ...

Is the WordPress error message "wp_register_style was improperly called" showing up on

I am facing an issue while trying to incorporate this code into my initial Wordpress template. It seems that the libraries for Bootstrap and my custom styles are not functioning as expected. Here is the code snippet in question. Any insights would be great ...

What causes the inconsistency between Chrome's print CSS emulation and the Print Preview feature?

My website is based on Bootstrap 3 and ensuring that certain pages print properly is crucial for our customers. While most of the site prints fine, we are having issues with modal dialogs. I have been experimenting with Chrome's (v42.0.2311.135 m) CS ...

On smaller screens, the dropup menu on the fixed bottom navbar seamlessly drops down into the navbar

Issue Almost done with my navbar (see code below), but the "Username" dropdown isn't behaving as expected. On larger screens it drops up, which is great, but on smaller screens it's dropping down into the navbar. If you resize the page, you&apos ...

Tips for getting a sticky table header and including a limited number of columns, each with checkboxes or input fields

Encountering issues while trying to implement functionality with a jQuery library. One specific problem is the inability to interact with checkboxes on sticky columns, as well as difficulties clicking and typing in text fields. I am utilizing the jQuery S ...

When it comes to using brackets and HTML, I keep receiving an error message indicating that there is no index file

I'm having trouble with this code - it works fine in Code Academy, but I am new to HTML and trying to practice outside of the platform. Every time I try to live preview in Brackets, I get an error message saying "make sure there is an html file or tha ...

Ionic's concealment feature fails to function properly for animations

I recently started learning about the Ionic framework and I'm attempting to incorporate a fade animation on a 'card' element using CSS. However, despite setting a 1-second transition duration, the targeted element simply disappears after a b ...

Creating a single div to influence the height of surrounding divs

Here is a fiddle you can check out: http://jsfiddle.net/thiswolf/RGe24/3/ to see the image div and the orange and middle divs stretch to match its height without padding the orange box towards the bottom. Here is the HTML code: <section class="les_hea ...

Is there a way to create a footer similar to this one?

I need to create a footer, but I'm struggling with placing a circle at the top half of the footer like this. Even though I can create a footer, I still encounter some issues. This is the code I have right now: .Footer { position: fixed; left: ...

What is the best way to create a responsive navigation bar design?

I'm trying to create a unique navigation bar that features a hexagon-shaped logo and 3 buttons aligned in a specific way. Check out the screenshot for reference here. Although I've managed to align everything perfectly on a fullscreen (1920x1080 ...

What is the best way to create a repeating Jquery loop in code?

Hey there! I've been working on creating a button that toggles the background color from white to yellow and back again using Jquery. However, I've hit a bit of a roadblock with implementing a loop function. If you'd like to take a look at m ...

The image source is not functioning properly to display the image, even though it is working perfectly on

I'm currently attempting to retrieve an image from Instagram. Everything seems to be in order with the image link on Instagram. However, when I try to use it within an img tag, it fails to fetch. One thing worth noting is that this particular image d ...

Showing one column fixed to the left and the other column scrollable to the right using CSS in Bootstrap 4

I have a bootstrap row with 2 cols inside. One col needs to be sticky on the left side, while the other col on the right side should contain multiple scrollable cards with text content. https://i.sstatic.net/ysYlP.png Looking at the image provided, the " ...

Add-on Group for Form Inputs - Is a style element missing? (Bootstrap 4)

I am looking for a way to incorporate a Bootstrap4 input group label between two input fields. While there are "prepend" and "append" styles available, in this scenario, I require a "center" style which seems to be missing. Does anyone have a solution for ...

When coding on Github pages, the behavior of code blocks can vary depending on whether

I am interested in obtaining the offline version, which can be seen here: https://i.sstatic.net/NKFSQ.jpg On the other hand, the online version has a different appearance: https://i.sstatic.net/133gH.jpg If you want to view the incorrect version, click ...

Obtain the text from an altered stylesheet in Firefox

I am currently programmatically updating stylesheets for a web page using JavaScript. My method involves having a local copy of the page and all associated assets stored on a server. After I finish making changes to the stylesheets, my goal is to save the ...

Error message: "An issue occurred: Unable to access undefined properties (specifically, borderRadius) in MUI react."

I recently created a navigation bar with an integrated search bar component. The styling for my search component was done using MUI styled from @emotion/styled in MUI library, where I applied a borderRadius: theme.shape.borderRadius. However, I encountere ...