What is the best way to display a collection of square Views in a FlatList in a react native application?

How can you create a scrollable square grid with two columns of squares in a FlatList using react-native and ensure it is responsive to different screen sizes?

Which CSS properties in react-native are necessary to achieve square shapes for each <Item/> within the FlatList?

I attempted to use aspectRatio without success.

While setting paddingTop : '50%' works for full rows, it does not work for the bottom as demonstrated here:

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


import React from 'react'
import {View, FlatList, StyleSheet, Dimensions} from 'react-native'

const screen_length = Math.max(Dimensions.get('window').height, Dimensions.get('window').width)

const screen_width = Math.min(Dimensions.get('window').height, Dimensions.get('window').width)
   
const length_factor = screen_length/844
const width_factor = screen_width/390

const StyleSheet.create.({
  container:{
    display: 'flex',
    flex:1,
    justifyContent: 'center',
    justifyItems: 'center',
    alignItems: 'center',
    alignContent: 'center',
    width: '100%',
    height:'100%',
    flexDirection: '100%'
  },
  square:{
    flex:1 ,
    aspectRatio: 1,
    backgroundColor: 'blue',
    borderColor: 'yellow',
    borderWidth: 5,
    borderRadius: 10,
    width:Math.round( width_factor * 150),
    paddingTop:'50%',
  }
 })

 const DATA = [ {id: 1}, {id:2} , {id: 3} ]

 const Item = ({item}) => {
   <View style = {styles.square} />
 }


export default function Test() {
  renderItem = ({item})=> {
    return(
      <Item />
    )
  }

  return(
    <FlatList
      data = {DATA}  
      renderItem = {renderItem}
      keyExtractor = {item => item.theme}
      numColumns = {2}
      style ={{flex:1, width:'100%', height: '100%'}}
      contentContainerStyle = {styles.container}
    />
  )
}

Answer №1

import React from 'react';
import { View, FlatList, StyleSheet, Dimensions } from 'react-native';

const screen_length = Math.max(
  Dimensions.get('window').height,
  Dimensions.get('window').width
);

const screen_width = Math.min(
  Dimensions.get('window').height,
  Dimensions.get('window').width
);

const length_factor = screen_length / 844;
const width_factor = screen_width / 390;

const styles = StyleSheet.create({
  square: {
    flexGrow: 0,
    flexShrink: 1,
    flexBasis: '50%',
    backgroundColor: 'blue',
    borderColor: 'yellow',
    borderWidth: 5,
    borderRadius: 10,
    paddingTop: '50%',
  },
  row: {
    flex: 1,
    justifyContent: 'space-around',
  },
});

const DATA = [{ id: 1 }, { id: 2 }, { id: 3 }];

const ItemComponent = ({ item }) => <View style={styles.square} />;
const renderItems = ({ item }) => <ItemComponent />;

const MainApp = () => {
  return (
    <FlatList
      data={DATA}
      renderItem={renderItems}
      numColumns={2}
      columnWrapperStyle={styles.row}
    />
  );
};

export default MainApp;

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

Strategies for identifying specific children in my particular situation

Here's a snippet of my code: <ul id='nav'> <li><h1 id='unique' class='title'>Topic</h1></li> <li><h1 class='toptitle'>Department</h1></ ...

Disable the scroll bar on a bootstrap modal

<span class="education"style="font-size:170%;line-height:150%;">&nbsp;Education <br> <small style=" color:gray;font-size:60%;">&nbsp; Blue Ridge University,2012-2014 </small> <br> <sma ...

How to optimize the loading speed of background images in an Angular application

Utilizing Angular v6, typescript, and SASS for my project. A CSS background image is set for the homepage, however, it's a large photo that always takes too long to load. Custom CSS: @import '../../../scss/variables'; :host { .wrapper { ...

Utilize orientation detection technology to ascertain the exact placement of an image

On my HTML page, I have a centered header (h1) with a title that displays in portrait mode above an image. When switching to landscape orientation, I want the image to move to the left side of the title. I've experimented with using <br> along ...

What is the best way to send props to a styled component without needing to convert them to transient props beforehand

Recently, I designed a custom Text component that accepts several props. These props are then forwarded to the styled component where specific styles are applied. However, I am facing an issue where I do not want these props to be passed down to the DOM, b ...

How to position a fixed element in relation to a wrapper div using HTML and CSS

I need assistance with positioning the floating box on the right side of the window on this particular page. My goal is to have this box relative to the white div containing all the text, so instead of it sticking to the window edge, it should float aroun ...

Mastering the art of changing text color based on element class name in CSS3

Is it possible to dynamically set the text color of a list item based on the class name of its nested span element? For example, if the span has a class of "green", the text color of the parent li should also be green. How can this be achieved? Demo:https ...

Customizing SharePoint Web Part Styles with CSS: Header Alignment Issue with Body_TEXT

I am currently working on branding a SharePoint website and have encountered an issue with aligning background colors for the title area and body of some web parts. Despite applying background colors, the alignment between the title and body areas is off ( ...

Modify the text color of the sliderInput element within a Shiny application

I am attempting to change the font color of the values (1,2,3,...10) in the sliderInput() from black to white, but I am encountering difficulties. How can I connect the slider with the CSS file to achieve this? ui <- fluidPage( tags$style(type = &quo ...

Seeking animated SVGs using CSS styling

I've been trying to animate my SVG icon, but I seem to be missing something. I'm still fairly new to CSS animations. The issue I'm facing is that the position of the SVG isn't correct when the website loads. Additionally, during the an ...

Background image in Bootstrap not covering entire web page

I am facing an issue where the background image is confined within the constraints of the login panel, and I'm unsure why. My goal is for the image to span the full width and height of the browser window. Any assistance on this matter would be greatly ...

Tips for effectively passing navigation as props in React Navigation with Expo

How can I correctly pass navigation as props to another component according to the documentation? The navigation prop is automatically provided to each screen component in your app. Additionally, To type check our screens, we need to annotate the naviga ...

The CSS hamburger icon displayed in the browser features three bars of varying heights

Looking to create a hamburger icon menu using only CSS? Check out my implementation below which includes three span tags in the HTML document. .sidebar-toggle { display: inline-block; } .sidebar-toggle span { display: block; width: 1.5rem; heig ...

Is it feasible to customize the css3 resize feature?

I'm curious - is there a way to customize the CSS3 resize property? div { resize: both; overflow: auto; } Basically, I am looking for a horizontal resize with a vertical bar instead of the default handle. Take a look at the images for reference. ...

Creating colorful containers using Bootstrap

Hey there, I am interested in creating small colored boxes to represent different meanings for each color. I came across this code snippet but I am unsure how to adjust the size: <div class="p-3 mb-2 bg-primary text-white">.bg-primary</d ...

The issue arises when trying to use ::v-deep in conjunction with v-dialog's content-class when using scoped scss

I've been working on styling the content of the Vuetify dialog component and have been using the content-class prop along with scoped styles to achieve this. Can someone explain the difference between the styles provided below? And also, any tips on h ...

Convert the background image (specified in the CSS with background-image) into a PHP variable

I am looking to create a product gallery featuring 5 products, each with its own background image attribute. I am using a loop to insert the product images and I want each loop to display a different background-image. One approach I have considered is usi ...

Lightbox2 is looking to reposition the caption to the right of the image

Can anyone help me understand how to move the caption, found in data-title, from underneath an image to the right of the image? I'm not very familiar with HTML/CSS, but it looks like the image is enclosed within a div called .lb-outerContainer, and t ...

Is it possible to deactivate an element based on a specific string present in the URL?

<div class="custom-class1"> <div class="custom-class2" id="custom-id1">hello 1</div> <div class="custom-class3" id="custom-id2">hello 2</div> <div class="custom-class4" id="custom-id3">hello 3&l ...

CSS hover effect not working while mouse is in motion

As a beginner in HTML, CSS, jQuery, and JavaScript, I've been trying to trigger a div when hovering over one area using the adjacent siblings code. However, I'm encountering an issue where if I move my mouse after triggering the event, it keeps r ...