Can a 1D array be utilized to create a 2D grid in React?

I needed to display a one-dimensional array in a 2D grid format with 3 rows and 3 columns. The array itself contains numbers from 1 to 9.

const array = Array.from({ length: 9 }, (_, i) => i + 1);

In my React component, I have it rendering as a series of div elements:

export default function App() {
  return (
    <div className="App">
      <div className="grid">
        {array.map((cell) => (
          <div className="cell">{cell}</div>
        ))}
      </div>
    </div>
  );
}

Currently, the cells are displayed stacked on top of each other as expected. I'm curious if there's a way to arrange them into a 3 x 3 grid using only CSS styles, without modifying the existing DOM structure.

Answer №1

Indeed, this discussion revolves around CSS Grid. Here is a basic HTML/CSS example that can be effortlessly transformed into React:

<!DOCTYPE html>
<html>
<head>
<style>
.grid {
  display: grid;
  grid-template-columns: auto auto auto;
  background-color: #2196F3;
  padding: 10px;
}
.cell {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.8);
  padding: 20px;
  font-size: 30px;
  text-align: center;
}
</style>
</head>
<body>
<h1>Grid Elements</h1>

<div class="grid">
  <div class="cell">1</div>
  <div class="cell">2</div>
  <div class="cell">3</div>  
  <div class="cell">4</div>
  <div class="cell">5</div>
  <div class="cell">6</div>  
  <div class="cell">7</div>
  <div class="cell">8</div>
  <div class="cell">9</div>  
</div>

</body>
</html>

Answer №2

  display: grid;
  grid-template-columns: auto auto auto;
  background-color: #2196f3;
  padding: 10px;
}
.grid-item {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.8);
  padding: 20px;
  font-size: 30px;
  text-align: center;
}
import "./styles.css";
const array = Array.from({ length: 9 }, (_, i) => i + 1);

export default function App() {
  return (
    <div className="App">
      <div className="grid-container">
        {array.map((cell) => (
          <div className="grid-item">{cell}</div>
        ))}
      </div>
    </div>
  );
}

https://codesandbox.io/s/busy-panka-mf4rhv?file=/src/App.js:0-314

Answer №3

Here's a neat demonstration showcasing the use of CSS grid for designing a layout using array.map().

You can execute it from this code snippet:

const array = Array.from({ length: 9 }, (_, i) => i + 1);

const App = () =>
<div className="App">
  <div className="grid">
    {array.map((cell, index) => (
    <div className="cell" key={cell}>{cell}</div>
    ))}
  </div>
</div>

ReactDOM.render(<App />, document.querySelector('#root'));
.grid {
 display: grid;
 grid-template-columns: repeat(3, 50px);
 grid-template-rows: repeat(3, 50px);
}

.cell {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #333;
  background-color: pink;
}

.cell:nth-child(even) {
  color: #fff;
  background-color: hotpink;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.production.min.js"></script>

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

Using Angular 6's httpClient to securely post data with credentials

I am currently working with a piece of code that is responsible for posting data in order to create a new data record. This code resides within a service: Take a look at the snippet below: import { Injectable } from '@angular/core'; import { H ...

Arranging columns with Bootstrap

I have a unique design using Bootstrap as shown below: <div class="row"> <div class="col-md-2"> 1 </div> <div class="col-md-8"> 2 </div> <div class="col-md-2"> 3 </div> </d ...

Unable to pass an event parameter using my this.handleChange function in react-native

Encountering an issue with the error message "undefined is not an object (evaluating 'event.preventDefault)" It appears that I am unable to pass an event parameter to the handleChange function in my child component, which is being rendered in the par ...

Is there a way to prevent the arrow up and down events from functioning on the MUI Menu?

My menu features a text field and a button. The text field is of type number, so ideally when I click on it and use the arrow up and down keys, the value should increase and decrease. However, instead of that functionality, the menu items are being selecte ...

When using Mongoose's save function within an async.each loop, it may

While working on an array processing task that involves saving and validating data asynchronously, I encountered an issue with duplicates. Here is the data I'm currently processing: var guests = [{ "email": "<a href="/cdn-cgi/l/email-protection" ...

Encountering issues with MediaSession.setPositionState() and seekto functionalities not functioning properly

Having trouble with MediaSession.setPositionState() not displaying the audio time and seekbar not behaving as expected. const sound= document.querySelector('sound'); function updatePositionState() { if ('setPositionState' in navigato ...

Create a function that binds a select dropdown to each table column header using JavaScript Object Notation (JSON), and then populate an HTML table with the

I have a dynamic table populated with JSON data, and I would like to add a select dropdown for each column. The challenge is that the number of columns is not fixed and they are also populated by JSON. Therefore, I want the select dropdown at the top of ea ...

Angular directive for resizing C3 charts

I've recently implemented a basic donut chart using C3, which I've enclosed in a directive and everything is functioning smoothly. Below is the code for my directive: angular.module('dashboardApp').directive('donutChart', fu ...

The React project encountered a build failure following the execution of the npm run command, resulting in the error code ELIFCY

I encountered an error while attempting to run my React project on localhost. Is there anyone who can provide assistance? Here is the error log: C:\Users\Intel\Desktop\burger-project>npm start > <a href="/cdn-cgi/l/email-prote ...

What is the best way to reset a dropdown list value in angular?

Is there a way to erase the selected value from an Angular dropdown list using either an x button or a clear button? Thank you. Code <div fxFlex fxLayout="row" formGroupName="people"> <mat-form-field appearance=&quo ...

Disabling the underline style on a4j:commandLink

Current Software Versions: Apache MyFaces 2.0 Rich Faces 4.3 Migration Challenge: We are in the process of upgrading from JSF version 1.2 to JSF version 2. One issue we have encountered is that there is no native support for sorting in rich:dataTable. ...

SharePoint 2013 on a mobile device does not support scrolling within iframes

Recently, I set up a SharePoint 2013 website with a few iframes. However, when I access the site on my mobile devices (iPad and Android), I am unable to scroll through the entire page by touching within the iframe. I attempted to solve this issue by inclu ...

Ensuring the modal is stored in one central location (Bootstrap)

I'm currently working on a website project using bootstrap, and I need to incorporate the same modal across all pages. Right now, I find myself duplicating the entire code in each HTML file to make it accessible on every page. However, this method is ...

"Adding dots" in a slideshow using HTML, CSS, and JS

I'm currently working on a slideshow that includes navigation dots at the bottom. Although the slideshow is functioning properly, I am encountering an issue where only one dot appears instead of the intended three in a row. Despite my research and att ...

Heroku Deployment Declined for Node.js and React Application

My Node.js + React app works perfectly on localhost, but when I try to push it to Heroku, the push gets rejected for some reason. Can any of you heroes out there help me figure out why? Here's the error log from Heroku Push: > NPM_CONFIG_P ...

Why am I encountering a warning about dangerouslySetInnerHTML and receiving empty content in Next.js?

First and foremost, I am aware that nesting <p> tags is not recommended. I have developed a Next.js application wherein one of my components sets rich text HTML in the following manner: <Typography dangerouslySetInnerHTML={{ __ ...

JavaScript's Math.round function does not always produce accurate results

After adding the specified line within the function, the code seems to encounter issues. parseLocalFloatCnt: num = Math.round(num*1.2); Is there a solution available for this problem? Your help is much appreciated. <!DOCTYPE html> <html> < ...

The prop type validation has failed: The prop `children` provided to `ForwardRef(Container)` is invalid. A ReactNode was expected

I've been racking my brain trying to figure out why I keep getting this warning. Even after commenting out all the code in both the page and component, the warning persists. It must be something simple that I'm just completely overlooking. Hopefu ...

Troubleshooting JavaScript Functions Failure Following AJAX XML Request

My current project involves developing an interactive map where users can select a year from the timeline and apply filters. This functionality is achieved through XML HttpRequest, which refreshes the SVG each time a selection is made. The SVG code for th ...

Properly accessing a JavaScript object acquired from a JSON file

I have a JSON file with data for 4 different items. Once I parse the JSON file, I see the output below. At that point, do I now have a JavaScript object? My goal is to access each item and add them to a plain object. How can I achieve this? The resulting ...