React-id-swiper: how can i get swiper‘s id after i swipered

Created on 5 Jan 2020  Â·  5Comments  Â·  Source: kidjp85/react-id-swiper

i am now writing a topbar。its style changes corresponding to the swiper id but i can't get swiper id after i swipered,is there a way ?

Most helpful comment

This should work:

import React, { useState, useEffect } from "react";
import Swiper from "react-id-swiper";
//
export default ({ children }) => {
  const [swiper, setSwiper] = useState(null);
  const [currentIndex, updateCurrentIndex] = useState(0);

  const config = {
    // Swiper config
  };

  useEffect(() => {
    if (swiper !== null) {
      swiper.on("slideChange", () => updateCurrentIndex(swiper.realIndex));
    }

    return () => {
      if (swiper !== null) {
        swiper.off("slideChange", () => updateCurrentIndex(swiper.realIndex));
      }
    };
  }, [swiper]);

  console.log({ currentIndex });

  return (
    <Swiper getSwiper={setSwiper} {...config}>
      {/* Loop over React children or do whatever to create your slides */}
      {children.map((Child, sliceIndex) => (
        <div key={sliceIndex}>{Child}</div>
      ))}
    </Swiper>
  );
};

All 5 comments

Hi. I met the same problem. Do you know the way to get the index of current page when swipering now?

Hi. I met the same problem too ! I file the function onTouchMove() but don't know how can use this ?

@kidjp85 How to get current active slide/page id after swiping?

This should work:

import React, { useState, useEffect } from "react";
import Swiper from "react-id-swiper";
//
export default ({ children }) => {
  const [swiper, setSwiper] = useState(null);
  const [currentIndex, updateCurrentIndex] = useState(0);

  const config = {
    // Swiper config
  };

  useEffect(() => {
    if (swiper !== null) {
      swiper.on("slideChange", () => updateCurrentIndex(swiper.realIndex));
    }

    return () => {
      if (swiper !== null) {
        swiper.off("slideChange", () => updateCurrentIndex(swiper.realIndex));
      }
    };
  }, [swiper]);

  console.log({ currentIndex });

  return (
    <Swiper getSwiper={setSwiper} {...config}>
      {/* Loop over React children or do whatever to create your slides */}
      {children.map((Child, sliceIndex) => (
        <div key={sliceIndex}>{Child}</div>
      ))}
    </Swiper>
  );
};

@NilapuAnusha I think you can find it from the doc or Live demo in Codesanbox

Was this page helpful?
0 / 5 - 0 ratings

Related issues

cweise picture cweise  Â·  6Comments

d4n1b picture d4n1b  Â·  5Comments

trevans24 picture trevans24  Â·  6Comments

maheshambiga picture maheshambiga  Â·  4Comments

jamland picture jamland  Â·  3Comments