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:


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

Scrollbars in Jquery are not visible anymore when adjusting the size of a div element, causing them to expand

I'm facing an issue with a layout containing a div that expands to the screen size upon clicking a button. Initially, the div has enough content to necessitate scrolling. However, after collapsing back to its original size, the scroll bar disappears a ...

Exploring Alternative Methods to Navigate Through Elements Using JQuery UI Autocomplete

After testing two different approaches: <div id = "team-search-container"> <label for="team-search" class = "text-center"> <input type = "text" id = "team-search"> </label> </div> With the following code sni ...

"Crafting a sleek card design using Material UI components in React JS

Exploring the world of material UI and looking to create a card with an image and footer. However, I'm facing challenges as there is no default option for adding a footer in the card. https://i.stack.imgur.com/xlxyb.png I want the image to be center ...

Various height divs are arranged in two columns and float accordingly

My goal is to have two columns that stack divs of varying heights in the order they appear. These divs are created dynamically, causing some challenges with alignment when floated at 50% width. For example, div #4 may end up being significantly taller tha ...

"Which is better for maximizing the efficiency of an image grid: CSS or Jquery? What are the key

As a UX Designer looking to enhance my coding skills, I must admit my code may not be perfect. Please bear with me as I navigate through this process. I am in the process of revamping my portfolio website. The original seamless grid was created using a Ma ...

Issues with Implementing Scroll Directive in Angular JS

Apologies for asking what may seem like a silly question. I'm still new to using AngularJS and recently came across a neat little scroll directive on http://jsfiddle.net/88TzF/622/. However, when I tried implementing the code in the HTML snippet below ...

Using CSS to break or wrap long words in text

I have a div that spans the width of the page. I'm looking to ensure that a very long word in this div breaks and wraps properly, so all the content stays within the screen width and doesn't overflow beyond 100%. Although I've attempted usi ...

Enhancing Image Quality in Internet Explorer 10

Here is my current situation: I am working on a web page with a responsive design. The layout of the page consists of two vertical halves, and I intend to display an image (specifically a PDF page converted to PNG or JPG) on the right side. The challenge ...

How to temporarily disable CSS hover effects

I have a menu with some links <ul id="nav"> <li> <a href="#">Project</a> <div class="subs"> <div> <ul> <li> <h3>Save</h3> <ul> <li> <a i ...

Can you explain the purpose of :not(style) ~ :not(style) in CSS?

Upon investigating, I found that Mui automatically included a :not(style) ~ :not(style) selector which required the use of !important in my sx to override. .css-1rb8ayf-MuiStack-root > :not(style) ~ :not(style) { margin-top: 40px; } .css-d13d9m-MuiSta ...

Tips on avoiding the collapse of the right div when positioned under a left float in a full page layout

Trying out a full page layout for the first time, with a left div serving as a block style nav. #admin_nav { width: 230px; height: 100%; background-color: #f9f9f9; border-right: 1px solid #ddd; float: left; } The content is on the rig ...

Create a single CSS style rather than using multiple CSS styles

I currently have multiple CSS styles applied: form#reply_form-c1r1.odgovor div#cmtforms-c1r1 input{color:red} form#reply_form-c2r1.odgovor div#cmtforms-c2r1 input{color:red} form#reply_form-c3r1.odgovor div#cmtforms-c3r1 input{color:red} form#reply_form-c4 ...

Modify the hover color of heading 1 only for hyperlink texts

I am attempting to adjust the hover color specifically for text that contains a link. Below is the CSS code I have tried, but it changes the color regardless of whether there are links present or not. h1, h2, h3, h4 { color:#3F3F3F; } h1:hover, h2:hove ...

Elements in Motion

Working on a parallax effect, I've managed to assign unique scroll speeds to (almost) every element. Moreover, these elements are programmed not to activate their scroll speed until they enter the viewport. Below is the JavaScript code for trigger co ...

Looking to tweak the date format in a Vue.js template?

I received the following format: 2019-01-08T11:11:00.000Z However, I need it to be in this format: 2019-01-08 Does anyone know how to achieve this date formatting without using the moment package? ...

Creating a React component with a circular loader that displays percentage and texts using Material-UI

I've developed a CircularLoader component using Material UI. The issue I'm facing is that when the variant is set to 'indeterminate', the loader should display without any percentage indication. However, if the variant is 'determin ...

How can you use HTML, CSS, and JavaScript to group objects with one color and then change the color of one specific object?

I have a set of 6 labels that act as buttons. When one is clicked, it changes from white to blue. If another label is clicked, the previously blue label turns white and the newly clicked one turns blue. Currently, the code below sets all labels to white b ...

Achieve a perfectly centered and responsive image placement on a webpage accompanied by a countdown timer

I've been trying to design an HTML page with a countdown feature, and I want to place an image above it that is centered and responsive. Despite my efforts, I haven't been able to achieve the desired responsiveness. I envision it looking like thi ...

What is the best way to decrease the font size of every element in the DOM?

Is there a way to decrease the size of all DOM elements by a specific amount? Currently, I am using Bootstrap styles where h5 is set at 14px and I need it to be 12px, and h1 is at 36px when I want it to be 34px, and so forth. I have considered two option ...

What is the best way to remove the box-model from an element?

Within my VueJS project, I am faced with nested elements that are generated dynamically like this: <container> <outerElement class="outer" v-for="obj in objects"> <innerElement class="inner" v-for="el ...