Utilize the Material UI grid in a horizontal orientation mapping

I have implemented a Card Grid using Material UI's Grid and Card components.

Below is the code I used :

class CardList extends React.Component {


  render() {
    const cardComponent = CardSeed.cards.map((card) => (
      <Card
        className="cards"
        key={'card-' + card.id}
        id={card.id}
        header={card.header}
        title={card.title}
        category={card.category}
        summary={card.summary}
      />
    ));
    return (
      <Grid direction="row" container spacing={4}>
        <Grid item xs={1}>
          {cardComponent}
        </Grid>
      </Grid>
    );
  }
}

export default CardList;

I am puzzled as to why the grid is displaying vertically instead of horizontally when using the map function, whereas it displays horizontally without it.

Answer №1

Make sure to include the Card component within each Grid item component, rather than nesting cards inside a grid item.

const CardComponent extends React.Component {
  const { card } = this.props;

  render() {
    return (
      <Card
        className="cards"
        id={card.id}
        header={card.header}
        title={card.title}
        category={card.category}
        summary={card.summary}
      />
    );
  };
};

class CardList extends React.Component {
  render() {
    return (
      <Grid container spacing={4}>
        {
          CardSeed.cards.map((card, i) => (
            <Grid key={'card-' + card.id} item xs={1}>
              <CardComponent card={card} />
            </Grid>
          ))
        }
      </Grid>
    );
  }
}

export default CardList;

Avoid passing the direction="row" props as it is already the default for a Grid component.

For more details, refer to the guide: https://mui.com/api/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

Can SKIP_FLIGHT_CHECK=true and openssl-legacy-provider be safely utilized in a React script when running npm start?

I've been working on a React app that contains outdated versions of the libraries listed in the package.json file. For example: "react": "^16.3.1", "react-scripts": "^3.0.1" ... While trying to install package ...

What is the best way to incorporate the chosen value into an array?

I'm currently working on implementing an Autocomplete feature and need some help with it: var arr=[]; const changeHandler = (value) => { // arr.push(value); // console.log("arr",arr) setItem(arr) } ...

Integrate the retrieved information into a new object and then proceed to export it

Hey there! I'm looking to retrieve data from an API and merge it with some existing data in an array of objects. The goal is to then export this combined data for use in another part of my web application. Check out the following code example: //expo ...

Day Change Triggers React [Native] View Update

I've been working on a React Native component that needs to update itself when the day changes, regardless of user interaction. Is there another method besides using setInterval for this task? If I use setTimeout in my viewDidLoad function with the n ...

Using the map method in JavaScript, merge two separate arrays to create a new array

In my ReactJS project, I have created two arrays using map function. The first array is defined as follows: const hey = portfolioSectorsPie.map(sector => sector.subtotal); const hello = portfolioSectorsPie.map(sector => sector.percentage) The value ...

Encountering a client component error with the app router in Next.js version 13.4.9

Encountering an error in Nextjs that persists until the 'use client' directive is removed. Warning: Rendering <Context.Consumer.Consumer> is not supported and will be removed in a future major release. Did you mean to render <Context.Con ...

Form-linked Progress Bar

This is a little project I created (for fun and learning purposes, even though it may not be the most optimized solution). If you're interested, here's the link to the code: https://codepen.io/paschos/pen/xxGXMQb I'm currently seeking assi ...

Encountering a "Cannot GET /" error message

We are currently utilizing Next.js/React.js for our front-end, along with a server.js file that facilitates image uploads to the public/images/uploads directory. However, we are encountering an error message stating Cannot GET / when attempting to run the ...

Tips for featuring the latest blog post at the top of a NextJS blog

I have a website built on Next JS with a blog page. The setup is correct, where the /blog page displays content based on slugs. Currently, new blog posts are appearing at the bottom of the page, under older ones. I want to reverse this so that when a new p ...

Having trouble importing Material UI and working with ClickAwayListener

For my current project, I am utilizing material-ui to implement the functionality for changing passwords. In this root file, I am importing several child components: Personalize.js import React, { useContext, useState } from 'react'; import Cook ...

A function that generates a table by rendering multiple arrays conveniently includes placeholders for empty data cells

When I combine arrays to display their data in a table, everything seems to go smoothly at first. However, there appears to be an issue where empty td tags are created after each loop from the map function, causing the rows to shift down. Test Data: expo ...

Does NextJs have a feature or function similar to the createRef() hook found in traditional ReactJs?

Trying to utilize a 3rd party package called ReactPhotoSphereViewer in NextJs to showcase panoramic images on the website. The package functions well in both NextJs and ReactJs. Below is the code that functions in ReactJs: import { ReactPhotoSphereViewer ...

When the Express API sends back a random number, Axios and React repeatedly call the API

I am facing an issue while creating a react component that displays a random number fetched from an API. The problem is that the number keeps re-rendering infinitely and the server console shows continuous requests from react. How can I fix this? I am curr ...

Leveraging the Spread Operator in Redux mapDispatchToProps with SweetAlert2

When I add the swal action creators to the mapDispatchToProps function like this: function mapDispatchToProps(dispatch) { return { getAnimal: (_id) => dispatch(getAnimal(_id)), ...swal } } The issue aris ...

Ways to link my frontend to a NodeJS backend that is publicly deployed rather than on localhost

When my NodeJS server is running on localhost PORT, I can successfully connect them both by using the following code: const PORT = 9000; const app = express() app.listen(PORT, () => console.log(`Server is up and running on PORT ${PORT}`)) app.use(bodyPa ...

Elevate state in React to modify classNames of child elements

I have a structured set of data divided into 6 columns representing each level of the hierarchy. When a user makes selections, their chosen location is highlighted with a dynamic CSS class name and displays the relevant data list. I've managed to impl ...

What is the reason behind the delayed mutation of the state when invoking the setState method in React?

Currently diving into the Forms section within the documentation of ReactJS. Just implemented this code snippet to showcase the use of onChange (JSBIN). var React= require('react'); var ControlledForm= React.createClass({ getInitialState: f ...

Render images conditionally as background elements for the body, ensuring they do not increase the height of pages with minimal content

Incorporating NextJS image components into the RootLayout of a NextJS component with negative z-indexes and absolute positioning was necessary to align them with dynamic content. However, an issue arose when these images at the base route '/' cre ...

Is it possible for a button to simultaneously redirect and execute a function using asynchronous JavaScript?

After browsing through several related posts, I realized that most of them were using href to redirect to a completely new webpage. However, in my JavaScript code, I have a button that utilizes the Material-UI <Link>. <Button component={Link} to= ...

MUI Material. Unique variant that respects style and color scheme guidelines

Context Currently, I am working on a small Proof of Concept project for our company. We are reevaluating our partnership with MUI and considering the idea of creating a new UI framework from scratch to customize our apps significantly. I believe this can ...