How to detect current slide in swiper js? - javascript

Working with swiper js for a slider and want to detect the current image/slide. how i can detect with HTML and JS? any idea?
<div class="swiper-container">
<div class="swiper-wrapper" align="center">
<div class="swiper-slide">
<img src="images/card_gold.png" width="80%" align="middle" onclick="desc(\'' + card1 + '\')">
</div>
<div class="swiper-slide">
<img src="images/card_platinum.png" width="80%" align="middle" onclick="desc(\'' + card2 + '\')">
</div>
<div class="swiper-slide">
<img src="images/card_silver.png" width="80%" align="middle" onclick="desc(\'' + card3 + '\')">
</div>
</div>
<!-- Add Arrows -->
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
</div>

its very easy. just use this:
swiper.activeIndex

As of May 2016 they have added the realIndex property!
swiper.realIndex
https://github.com/nolimits4web/Swiper/pull/1697
Notice:
property is returned as a string
property starts with 0, unlike
activeIndex in loop mode which in my case started with 1

Expanding on the answers that already refer to the realIndex property, here is a method for fetching the current slide's element by using realIndex as well as the slides property (an array containing all slides of the instance) to get the slide-element:
let index_currentSlide = instance_swiper.realIndex;
let currentSlide = instance_swiper.slides[index_currentSlide]
You can make use of this when constructing the instance by (for example) fetching the current slide whenever the slideChange event occurs and manipulating the element:
const instance_swiper = new Swiper(".swiper-container", {
on: {
slideChange: function () {
const index_currentSlide = instance_swiper.realIndex;
const currentSlide = instance_swiper.slides[index_currentSlide]
//
currentSlide.style.background = "red";
},
},
});

As far as I can see from their demos, the current slide always has the .swiper-slide-active class on the current slide element.
You can use jQuery selectors to get properties from the active slide. Here's an example of me fetching its image source:
$('.swiper-slide-active img').attr('src')

If you are using React.js here is how you could get activeIndex:
const swiperRef = useRef(null)
console.log(swiperRef.current.swiper.realIndex)
const [currentSlide, setCurrentSlide] = useState(0);
const [isLeftDisabled, setIsLeftDisabled] = useState(true);
const [isRightDisabled, setIsRightDisabled] = useState(false);
const updateIndex = useCallback(
() => setCurrentSlide(swiperRef.current.swiper.realIndex),
[]
);
// Add eventlisteners for swiper after initializing
useEffect(() => {
const swiperInstance = swiperRef.current.swiper;
if (swiperInstance) {
swiperInstance.on("slideChange", updateIndex);
}
return () => {
if (swiperInstance) {
swiperInstance.off("slideChange", updateIndex);
}
};
}, [updateIndex]);
<Swiper
className="swiper swiper-17-1"
modules={[Pagination]}
pagination={{
type: "fraction",
}}
slidesPerView={1}
ref={swiperRef}
/>
Key thing is you need to clean up evenlistener!!!!

That's how #Timsta solution can be used:
import { Swiper } from "swiper/react";
// state that has the current active index, which can be used to force re-rende other components
const [activeIndex, setActiveIndex] = useState(0);
// Trigger active index state update
<Swiper onRealIndexChange={(element)=>setActiveIndex(element.activeIndex)}>
{children}
</Swiper>

Here's a straightforward solution to this using onActiveIndexChange.
Using NextJs refs doesn't work. I highly recommend this approach if you are using SSR.
import React, { useState } from "react";
import type { Swiper as SwiperType } from "swiper";
const SwipeComponent: React.FC = () => {
const [currentIndex, setCurrentIndex] = useState<number>(0);
const updateIndex = (swiperInstance: SwiperType) => {
if (swiperInstance === null) return;
const currentSlide = swiperInstance?.activeIndex;
setCurrentIndex(currentSlide)
}
return (
<section className="mb-32 mx-16">
<Swiper
initialSlide={currentIndex}
onActiveIndexChange={updateIndex}
>
<SwiperSlide>
...
</SwiperSlide>
</Swiper>
</section>)
}

Related

how to create a react slider component

I was trying to make a react slider component but for some reasons it doesn't change/update the image on click instead it always displays the same picture. What i'm trying to achieve is when I click the button it updates index and the display image changes according to index position. Even though the index is updating the image is not changing. My attempt at creating the slider component -
import arrow from '../../img/arrow-outlined-crimson.png';
const Slider = ({ images }) => {
let index = 0;
const nextSlide = () => {
index+=1;
if (index > images.length - 1) {
index = 0
}
}
return (
<div className='slider'>
<div ref={sliderRef} className="wrapper">
<img src={images[index]} alt="" className="sliderImg" />
</div>
<img src={arrow} onClick={nextSlide} alt="Arrow" className="sliderIcon iconRight" />
</div>
)
}
export default Slider
Use React State instead of just variables.
Try this:
const [index, setIndex] = React.useState(0)
const nextSlide = () => {
setIndex(index + 1);
if (index > images.length - 1) {
setIndex(1)
}
}

Jquery code is not working in next js . Showing unexpected results but working on react

i am trying to implement an ui requirement. I want to add a active class name to the children div one at a time. 1st it will add the class in first child, and then the class will be removed and to be added in the 2nd child div. And it will infinitly itereate.
Here is my code in next js
$(".softwares_container").each(function () {
(function ($set) {
setInterval(function () {
var $cur = $set
.find(`.${st.active}`)
.removeClass(`${st.active}`);
//store inner html of current item
var $next = $cur.next().length
? $cur.next()
: $set.children().eq(0);
$next.addClass(`${st.active}`);
//store inner element of next item
//set inner html of current item to inner html of next item
var $next_inner = $next.children().eq(0);
setValue({
name: $next_inner.attr('alt'),
description: $next_inner.attr('data-info')
})
// setImage($next_inner.attr('src'))
}, 1000);
})($(this));
});
<div className={`softwares_container ${st.left_container}`}>
<div className={` ${st.img}`} alt="1">
<img src={ae.src} data-info="this is aftereffects" alt="After effects" />
</div>
<div className={st.img} alt="2">
<img src={pr.src} alt="Adobe Premiere pro" />
</div>
<div className={st.img}>
<img src={ps.src} alt="Adobe Photoshop" />
</div>
<div className={st.img}>
<img src={xd.src} alt="Adobe Xd" />
</div>
</div>
But it is not working.it is showing unexpected behaviour. It works fine in react .
Can anyone please give me an alternative solution or tell me how to fix the issue?
Here's the link where you can see the unexpected behaviour.
https://diptnc.ml/about
You can write an effect that sets the classname for elements in an array in a round-robin manner.
// Keep the interval id around so that
// it can be cleared when unsubscribing the effect.
let activeFxId;
/*
Applies active class to an array of HTMLElement in a round-robin manner.
*/
function activeFx(elements) {
activeFxId = setInterval(() => {
const elementsArr = [...elements];
let idx = elementsArr.findIndex((element) => {
return element.classList.contains('active');
});
if (idx === -1) {
idx = 0;
}
elementsArr[idx].classList.remove('active');
elementsArr[(idx + 1) % elementsArr.length].classList.add('active');
}, 2000);
return () => {
clearInterval(activeFxId);
};
}
How you provide this array of elements is left to you. An approach is to store a ref to the parent element containing them and pass that on to the function.
For example,
/* Example component */
import React, {useEffect, useRef} from 'react';
export default () => {
const ref = useRef();
useEffect(() => {
if (ref.current && ref.current.children) {
return activeFx(ref.current.children);
}
});
return (
<div ref={ref}>
<div>One</div>
<div>Two</div>
<div>Three</div>
</div>
);
};

How to wrap text typed with 'typed.js' ReactJs?

I'm building a web app with React that generates random movie quotes...
The problem arises when the quote is too long and it overflows outside the parent div...
I've tried altering the css with display flex and flex-wrap set to wrap. It does't work.
Here is my code.
import React from 'react';
import Typed from 'typed.js';
import './App.css';
import quotes from './quotes.json';
const random_quote = () => {
const rand = Math.floor(Math.random() * quotes.length);
let selected_quote = quotes[rand].quote + ' - ' + quotes[rand].movie;
return selected_quote;
}
const TypedQuote = () => {
// Create reference to store the DOM element containing the animation
const el = React.useRef(null);
// Create reference to store the Typed instance itself
const typed = React.useRef(null);
React.useEffect(() => {
const options = {
strings: [
random_quote(),
],
typeSpeed: 30,
backSpeed: 50,
};
// elRef refers to the <span> rendered below
typed.current = new Typed(el.current, options);
return () => {
// Make sure to destroy Typed instance during cleanup
// to prevent memory leaks
typed.current.destroy();
}
}, [])
return (
<div className="type-wrap">
<span style={{ whiteSpace: 'pre' }} ref={el} />
</div>
);
}
const App = () => {
return (
<>
<div className='background' id='background'>
<div className='quote-box'>
<TypedQuote />
</div>
<button onClick={random_quote}>New Quote</button>
</div>
</>
);
}
export default App;
I have this idea where I could implement a function that adds '\n' after like 10 words or like maybe after a '.' or ',' (I could implement some logic here). But this seems like a longshot. Is there a fancier way to do this?? Any help would be appreciated.
Try the property below on the parent container.
word-wrap: break-word;
or the below if you want to break words as well
word-break: break-all;

How to conditionally change visibility with React?

I am trying to change a div's visibility from hidden to visible using button click. But even when I am clicking the button, the visibility is not changing. I have logged the console after the clickHandler, and it still says false even after I set it to true inside the function. So far, I have this,
let clicked = false;
//change image on fortune cookie click
const clickHandler = (e) => {
e.target.setAttribute(
"src",
"https://i.ibb.co/cksx7kr/kisspng-fortune-cookie-drawing-clip-art-fortune-cookie-5b237469209879-9079770415290502171335.png"
);
clicked = true;
};
console.log(clicked);
return (
<div className="App">
<button onClick={clickHandler}>
<img
className="cookie"
src="https://i.ibb.co/9YQV2qq/kisspng-fortune-cookie-biscuits-bakery-drawing-clip-art-fortune-cookies-5b0ec5e3013c23-3980054715276.png"
/>
</button>
<div
className="fortuneMessage"
style={{ visibility: clicked ? "visible" : "hidden" }}
>
{fortune}
</div>
</div>
);
When you are using React, you need a state in order to have a DOM update. That would fork for you (don't forget to import useState at the top of your file) :
const [clicked, setClicked] = useState(false);
const [src, setSrc] = useState("https://i.ibb.co/9YQV2qq/kisspng-fortune-cookie-biscuits-bakery-drawing-clip-art-fortune-cookies-5b0ec5e3013c23-3980054715276.png");
//change image on fortune cookie click
const clickHandler = (e) => {
setSrc("https://i.ibb.co/cksx7kr/kisspng-fortune-cookie-drawing-clip-art-fortune-cookie-5b237469209879-9079770415290502171335.png");
setClicked(true);
};
console.log(clicked);
return (
<div className="App">
<button onClick={clickHandler}>
<img
className="cookie"
src={src}
/>
</button>
<div
className="fortuneMessage"
style={{ visibility: clicked ? "visible" : "hidden" }}
>
{fortune}
</div>
</div>
);
You'll need to use state instead of the plain clicked variable.
const [clicked, setClicked] = useState(false);
Call the setState function inside the clickHandler function instead of setting clicked to true.
setClicked(true);
in React, the variable is not two way binding.
The clicked variable in your function will only get to be true in the function itself but not outside the function
So in this case you need to use useState so that the clicked state will be re-rendered again with updated boolean
const [clicked, setClicked] = useState(false)
const clickHandler = () => {
setClicked(true)
}
so that your clicked variable will be updated, hence the css will be updated again.
for more reference with useState can check their documentation https://reactjs.org/docs/hooks-state.html

React JS Infinite Carousel

I'm building a portfolio app in React JS and one of my pages is an About Me page. I stumbled upon a youtube video that builds an infinite carousel using vanilla JavaScript, and during my initial testing it worked. However, when I navigate away from my 'About Me' page and return, it explodes with a "TypeError: Cannot read property 'style' of null" within my About Me component "stepNext; src/components/about-me/AboutMe.js:34".
import React from "react";
import "./AboutMe.css"
import { Button,
Fade,
Grow,
Typography } from '#material-ui/core'
import { ArrowBackIos, ArrowForwardIos } from "#material-ui/icons";
import { Background, Adventures, Hobbies } from "./about-me-components/index";
export const AboutMe = () => {
const slider = document.querySelector('.slider-about-me')
const carousel = document.querySelector('.carousel-about-me')
let direction = 1
const stepPrevious = () => {
if (direction === 1) {
slider.appendChild(slider.firstElementChild)
}
direction = -1
console.log("Previous", direction)
carousel.style.justifyContent = 'flex-end'
slider.style.transform = 'translate(33%)'
}
const stepNext = () => {
if (direction === -1) {
slider.prepend(slider.lastElementChild)
}
direction = 1
console.log("Next", direction)
carousel.style.justifyContent = 'flex-start'
slider.style.transform = 'translate(-33%)'
}
const sliderAppend = () => {
if (direction === 1) {
slider.appendChild(slider.firstElementChild)
} else if (direction === -1) {
slider.prepend(slider.lastElementChild)
}
slider.style.transition = 'none'
slider.style.transform = 'translate(0)'
setTimeout(() => {slider.style.transition = 'all 0.5s'})
}
return (
<>
<Fade
in={true}
timeout={1500}
>
<div
id='about-me-container'
>
<div className="controls">
<div
className='arrow-span-about-me arrow-left-about-me'
>
<Button
className='button-about-me arrow-about-me'
variant='contained'
onClick={stepPrevious}
>
<ArrowBackIos
className="arrow-back-about-me"
/>
</Button>
</div>
<div
className='arrow-span-about-me arrow-right-about-me'
>
<Button
className='button-about-me arrow-about-me'
variant='contained'
onClick={stepNext}
>
<ArrowForwardIos
className="arrow-forward-about-me"
/>
</Button>
</div>
</div>
<div
id="about-me-carousel-container"
>
<div
className='carousel-about-me'
>
<div
className='slider-about-me'
onTransitionEnd={sliderAppend}
>
<section className='text-white'><Background /></section>
<section className='text-white'><Adventures /></section>
<section className='text-white'><Hobbies /></section>
</div>
</div>
</div>
</div>
</Fade>
</>
)
}
The only reason I chose this route is because I haven't been able to find a half decent infinite carousel module with easy customization abilities. As much as I would prefer for this to work, I'm open to suggestions and/or solutions. Much appreciated!
I would suggest using useRef instead of document.querySelector
document.querySelector happens outside of that lifecycle, making what it returns unreliable, while refs happen within it. (Though doesn’t get reset because of a lifecycle event like a re-render.) This ensures the object returned by the ref is an accurate representation of the current state of the virtual DOM.
I think this is the reason why you are encountering the said error when you go away and back from the About Page.
Here's an example:
https://codesandbox.io/s/objective-fast-vhc27?file=/src/modalAndButton.jsx:531-648

Categories