'Swiperjs. How can I pass custom props to SwiperSlide and get it onSlideChange function?

I am in a different situation. I am using Swiper.js for my React app. I need to change app theme color on slide changes and it have to be dynamic. That's I need to pass some props to SwiperSlide and get this props on slide change. How can I handle that ?

    <Swiper
      id="pathway-slider"
      slidesPerView={1}
      onSlideChange={(swiper) => {
        console.log("Slide index changed to: ", swiper);
      }}
    >
      <SwiperSlide>
          Slide 1
      </SwiperSlide>
      
      <SwiperSlide>
          Slide 2
      </SwiperSlide>
    </Swiper>

When I console.log(swiper) it gives me huge object where I can access activeSlideIndex or etc. But how can I pass custom data to that ?



Solution 1:[1]

A solution for people trying to use material UI and swiperis to wrapper the swiper component in amaterial styled componentand then pass your props through thesx={{}}for some reason this doesn't throw atypescript flag`

Import styled

import { styled } from "@mui/system";

Wrapper Swiper in styled

const StyledSwiper = styled(Swiper)(({ theme }: any) => ({
  padding: "20px 0 70px 0",
}));

Add Custom Swipper to your page or component

<StyledSwiper
        ...some_default_PROPS
        sx={{
          "& .swiper-slide": {
            transition: "all 3s ease",
            transform: isHomePage ? "scale(0.8)" : "initial",
          },
          "& .swiper-slide-active": {
            transform: isHomePage ? "scale(1.1)" : "initial",
          },
          "& .swiper-pagination": {
            bottom: "0",
          },
        }}
      >  {data?.length > 0 &&
          data.map(((node,index)) => (
            <SwiperSlide key={node?.id}>
              <div> Slide {index}</div>
            </SwiperSlide>
          ))}
      </StyledSwiper>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ice_mank