最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Multiple items on Material UI Carousel - Stack Overflow

programmeradmin10浏览0评论

I'm using the following Material UI Carousel library and I'm having trouble understanding how can I create multiple items for the carousel.

I have searched in the docs, no solution there, tried to manipulate with CSS by defining width like this:

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

Didn't worked either.

Here is my code:

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


   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;

Right now each slide contains one Item, my goal is to reach 3 items on each slide.

How can I use multiple items in one slide using Material UI Carousel?

Codesandbox

I'm using the following Material UI Carousel library and I'm having trouble understanding how can I create multiple items for the carousel.

I have searched in the docs, no solution there, tried to manipulate with CSS by defining width like this:

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

Didn't worked either.

Here is my code:

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


   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;

Right now each slide contains one Item, my goal is to reach 3 items on each slide.

How can I use multiple items in one slide using Material UI Carousel?

Codesandbox

Share Improve this question edited Mar 29, 2021 at 22:44 Yotam Dahan asked Mar 29, 2021 at 21:04 Yotam DahanYotam Dahan 6992 gold badges11 silver badges36 bronze badges 5
  • Send me the plete demo using this: codesandbox.io – m4n0 Commented Mar 29, 2021 at 22:12
  • @m4n0 codesandbox.io/s/angry-davinci-0sj9h?file=/src/App.js – Yotam Dahan Commented Mar 29, 2021 at 22:44
  • 1 How about this? x2zto.csb.app – m4n0 Commented Mar 30, 2021 at 0:03
  • @m4n0 That works! but I do have one question, how can I move only one item on each click? – Yotam Dahan Commented Mar 30, 2021 at 7:52
  • For that you might have to change the structure a bit or make use of custom JS to override. There is no such setting in the docs. You would have to alter the transform properties. – m4n0 Commented Mar 30, 2021 at 9:29
Add a ment  | 

2 Answers 2

Reset to default 9

Shalom!
The problem is inside the Carousel ponent.

I'm new with Material UI, but it seems that every array element gets a "page" on the slider.

So what i've done and it gave me the result you are looking for looks something like this:

    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 chose 3 items per slider. items array contains array of Cards.

Multiple items on Material UI Carousel

I recently had to implement a carousel in a React project where I needed to group array elements into chunks to display them as slides. Here's how I achieved it:

  1. Create a function to group array elements into chunks:
    function groupIntoChunks(array, chunkSize) {
      const output = [];
      let currentChunk = [];
    
      array.forEach((item, index) => {
        currentChunk.push(item);
    
        if ((index + 1) % chunkSize === 0 || index === array.length - 1) {
          output.push(currentChunk);
          currentChunk = [];
        }
      });
    
      return output;
    }
  1. Use the groupIntoChunks function to group the array elements for carousel slides:
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'));

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

return (
  <Carousel animation="slide" autoPlay={false} navButtonsAlwaysInvisible height={'300px'}>
    {groupIntoChunks(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' }}>
            {/* Display your review content here */}
          </Grid>
        ))}
      </Grid>
    ))}
  </Carousel>
);

Explanation: The groupIntoChunks function takes an array and a chunk size as input and returns an array of arrays, each containing elements of the original array grouped into chunks. Then, we use this function to group our reviews array into chunks based on the device size (mobile, tablet, or desktop).

This approach allows us to display the reviews as carousel slides with the appropriate number of reviews per slide, ensuring a responsive and user-friendly experience.

I hope this helps! Let me know if you have any questions.

发布评论

评论列表(0)

  1. 暂无评论