Creating two columns using React and Material-UI Grid while utilizing just one map function for iteration

I am facing a challenge with Material-UI Grid. I want to display the information from my map function in two columns instead of one. I tried adding another Grid item sm={6} and using the same map function, which resulted in two columns but with identical information. How can I break the grid into two separate columns when iterating through data with just one map function?

const renderData = (person, picture, index) => {
        return (
            <Paper className={classes.Paper}>
                <img src={person.picture.large} />
            </Paper>
        )
    }
return (
        <div className={classes.sectionContainer}>
            <h3 className={classes.title}>Follow our instagram!</h3>
            <h3 className={classes.title}>@platformdanceshowcase</h3>
            <Grid direction='row' container spacing={1}>
               <Grid item sm={6}>
                {previewData.slice(0, visible).map(renderData)}
               </Grid>
            </Grid>
            <Container className={classes.extendButtonArea}>
                {visible < previewData.length && (
                    <Button className={classes.extendButton} onClick={loadMore}>
                        View More...
                    </Button>
                )}
            </Container>
        </div>
    )
}

Any assistance is much appreciated as I seem to be stuck in a loop, confusing myself even more. Thank you in advance!

Answer №1

If the question is unclear, perhaps providing a screenshot or sketch of your goal would help clarify things?

It seems unusual to have 2 return functions in the renderData component. I'll assume the first represents elements of previewData and the second represents columns as mentioned in your question.

Based on my understanding, it sounds like you want two side-by-side columns displaying data from previewData starting at index 0 up to a certain point. One approach could be adjusting your code this way:

<Grid direction='row' container spacing={1}>
    <Grid container item sm={6}>
        {previewData.slice(0, visible).map((renderData, i) => 
            i % 2 === 0 ? renderData : <></>)}
    </Grid>
    <Grid container item sm={6}>
        {previewData.slice(0, visible).map((renderData, i) => 
            i % 2 === 1 ? renderData : <></>)}
    </Grid>
</Grid>

The map function offers an index parameter that can help distribute items into different columns. This code snippet can also be adjusted to display the first half of items on the left column and the second half on the right.

<Grid direction='row' container spacing={1}>
    <Grid container item sm={6}>
        {previewData.slice(0, Math.floor(visible / 2)).map(renderData)}
    </Grid>
    <Grid container item sm={6}>
        {previewData.slice(Math.ceil(visible / 2), visible).map(renderData)}
    </Grid>
</Grid>

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

Moving Images from Firebase to Google Drive

I'm looking for a way to automatically copy photos uploaded to a Firebase DB to a designated Google Drive folder. Is there a way to achieve this while the photos are getting uploaded to Firebase or once the last photo is uploaded? The link below seems ...

Include a flexible div in the hero section and change the position when resizing the screen

Looking to achieve a specific layout with only two resolutions in mind (767px minimum and maximum). For screens larger than 767px, display two divs side by side: one with text on the left and the other with an image on the right. The text remains in a fi ...

The issue at hand is that Redux Persist state fails to persist data fetched from an API using

When fetching an API using axios, the action is triggered after the "persist/REHYDRATE" action, resulting in the message "redux-persist/autoRehydrate: 1 actions were fired before rehydration completed...." If I delete tweets one by one and then refresh my ...

Can the underline height be adjusted when a developer uses `text-decoration: underline;` in CSS to generate an underline effect?

Can the height of the underline created using text-decoration: underline; in CSS be adjusted? I used CSS to apply an underline to the word "about" with an 'id' of '#title4' but I want to increase the space between the word and the unde ...

What is the best method for displaying plain text using the br tag?

My component looks like this: class News extends Component { state = { isSimple: this.props.isSimple } render() { return ( <div> <div className="extended">extended</div> simple text </div&g ...

A guide to utilizing CSS to showcase the content of all four div elements in HTML body simultaneously

Is there a way to use CSS to display the content of all 4 divs in the same place on the HTML body, based on the URL clicked? Only one div should be displayed at a time in the center of the page. For example, if URL #1 is clicked, it should show the conten ...

Unable to adjust the text color to white

As someone who is new to Typescript, I'm facing a challenge in changing the text color to white and struggling to find a solution. I'm hoping that someone can guide me in the right direction as I've tried multiple approaches without success ...

Angular2's hidden feature isn't functioning properly

There is a common suggestion to use *ngIf better than [hidden] but in my scenario, I want to keep the element in the DOM without it being visible. In my component.html file, I have: <article #articleId id="bodyArticle" [hidden]="isClicked"></art ...

The functionality of Angular Datepicker is disrupted when scrolling through the page

Coding in HTML <div class="col-5 col-md-3 px-0 daterange-picker"> <div class="form-group"> <div class="input-group"> <input type="text" id="second ...

Customizing CSS by replacing link file styles with code in the HEAD section

UPDATE: After further examination, it appears that the code is functioning correctly. My apologies for any confusion. I am attempting to override certain CSS rules on specific pages. Below is an example of my approach. Can anyone confirm if this is a vali ...

Troubleshooting React on an Apache Server: A Comprehensive Guide

An interactive React application utilizing React Router has been successfully deployed on an Apache server. After making modifications to the .htaccess file, most of the routes function correctly as intended. Some specific routes within the app rely on us ...

<ol><li>Arranges elements in a peculiar way if the image is aligned to the left</li></ol>

Explore this comprehensive presentation on combining PDFs online. In this blog post, I have encountered two instances of <ol><li> formatting. The first one is styled properly using the following CSS: .post_content ul, .post_content ol ...

Why does the CORS Error persist in Django Rest Framework despite my efforts to fix it?

I have a React frontend connected to a DRF Backend. Currently, I am utilizing axios in the frontend to refresh a JWT access token. The refresh token is included in every request as an HttpOnly cookie and Simple JWT library in the DRF backend handles the re ...

Overlay Image on Card, Overflowing into Card Body

I currently have a webpage featuring cards. Each card includes a thumbnail at the top with an overlay. The main content of the card needs to be positioned outside of the overlay, but it ends up overflowing onto it. Take a look at the demo: https://codepe ...

What is the process for implementing a grid with 5 columns on larger screens and 2 columns on smaller screens using reactjs?

I am currently working on building a Grid using material UI and reactJs. I found the guidelines on this link https://mui.com/system/react-grid/. However, there seems to be an issue with creating 5 columns in the grid. I attempted to create a custom grid ...

Is there a way to customize the focusVisible property for a Material UI radio button?

Currently, I am working with Material UI's Radio button component. I am looking to customize the focusVisible property specifically for when users navigate using keyboard only, and apply unique styles to the checkbox element. While I can define styl ...

Issue with displaying strings in the value attribute of a function

When I call onClick on a Material-UI MenuItem and set the value attribute as a string, the event function interprets the value as zero. If I add a value="sometext" to other elements like a button, it works perfectly. Even though I am new to this, it seems ...

Changing the width of an HTML table does not produce any noticeable results

I attempted to create a striped table with 5 columns. The desired column sizes are: 10% width --- 10% width --- 40% width --- 20% width --- 20% width However, my current code is not achieving the correct widths (the 'description' column does n ...

What is the best method for retrieving data from a specific collection in MongoDB?

Within the code snippet below, on the 4th line, 'Messages' is the name of my MongoDB collection that I created in another file. When I attempt to retrieve data from this collection, no errors occur. However, when I specify the name of a differen ...

Attempting to reduce the width of the dig when it reaches 400

I have a square element with a click event that increases its size by 50 pixels on each click. However, once it reaches a size of 400 pixels, the size decreases by 50 pixels with every click instead. Additionally, when the size of the square reaches 100 p ...