Numerous items featured on the Material UI Carousel

I've been utilizing the Material UI Carousel library for my project, but I'm struggling to figure out how to display multiple items on each slide of the carousel.

I checked the documentation but couldn't find a solution. I also tried adjusting CSS properties like setting the width in the following way:

.item{
    margin: 0 auto;
    text-align: center;
    width: 30%;
}

However, that didn't work as expected.

Below is a snippet of my code:

function Home() {
    var items = [
        {
            name: "Pizza Begin",
            link: "pizza-begin.co.il",
            image: Begin
        },
        {
            name: "Mia Luz",
            link: "mia-luz.com",
            image: Mia
        },
        {
            name: "Nuda Swim",
            link: "nudaswim.com"
        }
    ];

    return (
        <>
            <Carousel navButtonsAlwaysInvisible={true} animation="slide" activeIndicatorIconButtonProps={{className: "activeIndicator"}}>
                {items.map((item, i) => <Item key={i} item={item} />)}
            </Carousel>

        </>
    );
}

function Item(props) {
    return (
        <Paper className="item">
            <img className="imageCarousel" src={props.item.image} alt={props.item.name} />
            <h2 onClick={() => { window.location.href = props.item.link; }}>{props.item.name}</h2>
        </Paper>
    )
}

export default Home;

Currently, each slide only contains one Item element, but I want to display three items per slide. How can I achieve this using Material UI Carousel?

For more context, you can view the implementation on Codesandbox.

Answer №1

Greetings!
The issue resides within the Carousel component.

Although I am relatively new to Material UI, it appears that each element in the array corresponds to a "page" on the slider.

To achieve the desired outcome, here is an approach that I took:

    const sliderItems: number = data.length > 3 ? 3 : data.length;
  const items: Array<any> = [];

  for (let i = 0; i < data.length; i += sliderItems) {
    if (i % sliderItems === 0) {
      items.push(
        <Card raised className="Banner" key={i.toString()}>
          <Grid container spacing={0} className="BannerGrid">
            {data.slice(i, i + sliderItems).map((da, index) => {
              return <SubCategory key={index.toString()} item={da} />;
            })}
          </Grid>
        </Card>
      );
    }
  }
  return (
    <Carousel animation="slide" autoPlay={false} cycleNavigation timeout={300}>
      {items}
    </Carousel>
  );
};

I opted for 3 items per slider. The 'items' array consists of arrays of Cards.

Answer №2

Implement Carousel with Multiple Items using Material UI

In a recent React project, I encountered the need to create a carousel that displayed array elements as slides by grouping them into chunks. Here's how I tackled this task:

  1. Develop a function to group array elements into chunks:
function splitArrayIntoChunks(array, chunkSize) {
      const result = [];
      let currentChunk = [];
    
      array.forEach((item, index) => {
        currentChunk.push(item);
    
        if ((index + 1) % chunkSize === 0 || index === array.length - 1) {
          result.push(currentChunk);
          currentChunk = [];
        }
      });
    
      return result;
    }
  1. Utilize the splitArrayIntoChunks function to organize array elements for the carousel:
import { Grid, Stack, Typography } from '@mui/material';
import Carousel from 'react-material-ui-carousel';

// Define your reviews array
const reviews = [
  // Array of review objects
];

// Determine if it's a mobile or tablet device
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
const isTablet = useMediaQuery(theme.breakpoints.down('md'));

// Decide the chunk size based on the device
const chunkSize = isTablet ? (isMobile ? 1 : 2) : 3;

return (
  <Carousel animation="slide" autoPlay={false} navButtonsAlwaysInvisible height={'300px'}>
    {splitArrayIntoChunks(reviews, chunkSize).map((group, groupIndex) => (
      <Grid container key={groupIndex} sx={{ gap: '20px', justifyContent: 'center', alignItems: 'center', py: '20px', height: '300px' }}>
        {group.map((review, reviewIndex) => (
          <Grid item key={reviewIndex} xl lg md sm xs sx={{ border: '2px solid', borderColor: 'primary.neutral100', height: '100%', px: 2, py: 4, borderRadius: '8px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', cursor: 'grab' }}>
            {/* Add your review content here */}
          </Grid>
        ))}
      </Grid>
    ))}
  </Carousel>
);

Explanation: The splitArrayIntoChunks function divides an array into subarrays with a specified chunk size. We leverage this function to structure our reviews array into chunks according to the device type (mobile, tablet, or desktop).

This method enables us to exhibit the reviews as carousel slides with the optimal number of reviews per slide, ensuring adaptability and user satisfaction.

I trust this explanation assists you! Feel free to reach out if you have any queries.

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

Utilize the body tag to divide elements in ReactJS

Is there a way to assign different body tags to specific components? For example, I want to apply one body tag to the dashboard component and a different one for the sign up page component. ...

The `x-forwarded-host` header does not align with the `origin` header when using the value from a forwarded Server Actions request

While attempting to utilize the Vercel AI Chatbot example on Github Codespaces as my development environment, I am running into a familiar issue outlined in this specific GitHub problem. The error message reads as follows: "x-forwarded-hostheader with val ...

Having trouble locating a custom font while using React in conjunction with Material UI

My MUI theme is set up like this: export default createMuiTheme({ typography: { fontFamily: '"Nunito Sans", "Helvetica", "Arial", sans-serif', fontWeightLight: 300, fontWeightMedium: 600, fontWeightRegular: 400 } } }); I ...

Having trouble toggling the camera (front to rear) in a React application while using WebRTC's MediaDevices feature

Here is a demonstration of the issue I am facing with the camera switch functionality. If anyone has any suggestions or solutions, please feel free to share. The problem arises when trying to use the mediaStream API and react-webcam library to enable came ...

Guide on creating uniform heights and widths for images with varying dimensions utilizing CSS (and percentage values)

Is there a way to ensure that all images maintain the same height and width using CSS percentages, rather than set pixel values? I'm working on displaying images in circles, where most are uniform in size but a few outliers distort the shape. The wide ...

Is there a way to reach a different function within the value of the react Context.Provider?

Right now, I am learning how to utilize the react context API. Within my react Provider class, I have some state data and functions stored in the value={}. But I am curious, how can I call a function inside this value from another function within the same ...

Preserving the Selected Date on the Calendar Even After the PHP Variable is Passed

I am currently using the calendar code below with a slight modification that I implemented. However, I have encountered an issue where when I select a date, the calendar successfully highlights the selected date. But once I pass this selected date along ...

Tips for adding an HTML code snippet to an HTML iframe with the help of jQuery

Is there a way to dynamically append an HTML code snippet to an HTML iframe using jQuery? I have stored an HTML code snippet in a MySQL Database using PHP, and I am now attempting to retrieve that snippet and add it to the iframe using jQuery. $( document ...

An error has occurred: Expected a string as the element type in React when attempting to update the state

I encountered an issue while trying to update the state after fetching data. Error: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components), but received: undefined. This could be due to forgett ...

react-ga4 is sending multiple view events repeatedly

After setting up a Google Analytics account and creating a new property, I integrated the tracking ID with react-ga4 for my Album ItemPage as shown below: const ItemPage = () => { const {user} = useContext(AuthContext); let { item } = useParams ...

Properly integrating vue-social-sharing in Vue.js 3: A step-by-step guide

Currently, I am facing an issue while trying to implement vue-social-sharing in my project. The error message I receive is "Component is missing template or render function." Below is a snippet of my main.js file: import {library} from '@fortawesome/f ...

Transferring content files from a nuget directory to a specific destination folder

I am dealing with a nuget package that includes css files as content. My goal is to have these css files copied to a specific directory upon importing the package into a project, without requiring the project's structure to match exactly. Is there a ...

Modules failing to load in the System JS framework

Encountering a puzzling issue with System JS while experimenting with Angular 2. Initially, everything runs smoothly, but at random times, System JS struggles to locate modules... An error message pops up: GET http://localhost:9000/angular2/platform/bro ...

Unable to change the color of the RaisedButton component in Material-UI

Struggling to alter the color of the material-ui RaisedButton with inline style customization using backgroundColor: '#fb933c', yet it continues to display the default color. ...

What is the best way to add text input to a dropdown selectbox?

I am looking to create an input text within a select box using Jquery. If the user enters a value in the input box, the result should show the input type text value. If the user selects an option from the select box, the results should display the selecte ...

Adding a key prop to BlueprintJS Tree structure is essential for maintaining

I am currently incorporating BlueprintJS UI components into my ReactJS web application. I am facing a warning while using the Tree component to display a file explorer: Each child in an array or iterator should have a unique "key" prop. Check the render m ...

The fixed header column doesn't remain sticky

I am working on fixing the first column in my table to remain static on mobile devices so that users can easily identify the data they are viewing when scrolling. While the td elements in the table work perfectly as intended, the column header continues to ...

What is the best way to design three flexible divs using display: table without the use of JavaScript?

https://i.sstatic.net/bEC4Y.png Is it possible to create a responsive layout with three divs that behave in the following way: When the viewport is narrow, the three divs stack on top of each other When the viewport is average, the first div spans full ...

How can I duplicate an element twice in AngularJS, without having them appear right after each other?

Within my AngularJS template html file, I am faced with a dilemma regarding an html element: <div>This is a complex element that I want to avoid typing multiple times</div> My challenge is that I need this element to show up twice on my websi ...

Drag to rotate using JavaScript when the mouse is pressed down

I am experimenting with making a spinning wheel rotate as the user drags the mouse over it. The wheel consists of 3 pieces, so I have individually mapped each image to target the specific section of the wheel that I want to rotate. Currently, it is funct ...