React-id-swiper: onIndexChanged

Created on 20 Mar 2020  路  1Comment  路  Source: kidjp85/react-id-swiper

i need to track the index but found nothing like onIndexChanged. How can i do that ? Thanks

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 comments

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>
  );
};

Was this page helpful?
0 / 5 - 0 ratings

Related issues

cweise picture cweise  路  6Comments

Pixel-Daze picture Pixel-Daze  路  4Comments

d4n1b picture d4n1b  路  5Comments

yuschick picture yuschick  路  5Comments

davemin picture davemin  路  6Comments