'React Swiper 6.8.4 only Shows Slides when resizing window or applying Filter
I am pretty new to coding and react and I am having an issue with Swiper 6.8.4 in my React app since i added a FilterMethod. My idea was to have a Slider with some Projects/Images as Slides in it, and be able to filter these Slide by a multiple checkbox filter. So far everything is working fine. I am able to check multiple checkboxes and projects are filtered correctly, But i think there is a problem when initialising swiper: Every time i reload the page Swiper doesnt show any slides until i resize the page or check some filter checkboxes.
Here is my Code: Please can somebody help me!
import React, { useState, Fragment, useEffect } from "react";
import allData from '../allData';
import { Swiper, SwiperSlide } from 'swiper/react';
import SwiperCore, { Autoplay,Navigation, Pagination, Controller, Thumbs } from 'swiper';
import 'swiper/swiper-bundle.css';
import './styles.css';
SwiperCore.use([Autoplay,Navigation, Pagination, Controller, Thumbs]);
const project = [
{ type: "Web" },
{ type: "3D" },
{ type: "Photography" },
{ type: "Print" },
{ type: "Practice" }
];
export default function App() {
const [type, setType] = useState([]);
const [filteredType, setFilteredType] = useState([]);
const handleChange = e => {
if (e.target.checked) {
setType([...type, e.target.value]);
} else {
setType(type.filter(id => id !== e.target.value));
}
};
useEffect(() => {
if (type.length === 0) {
setFilteredType(allData);
} else {
setFilteredType(
allData.filter(project =>
type.some(category => [project.type].flat().includes(category))
)
);
}
}, [type]);
const [show, toggleShow] = React.useState(false);
return (
<div>
<Swiper
slidesPerView={'auto'}
onSlideChange={() => toggleShow(!true)}
loop={false}
centeredSlides={true}
direction={'horizontal'}
spaceBetween={100}
slideToClickedSlide={true}
pagination={{
"type": "fraction"
}}
className="mySwiper">
{filteredType.map((project, index) => (
<SwiperSlide className="swiper-slide">
<img className="img-slide" src={project.image} alt=""/>
<div className="project-info">
{show && <div className="info" key={project.id}>{project.info}</div>}
<div className="text">{project.id} / {project.title}</div>
</div>
</SwiperSlide>
))}
</Swiper>
<div className="filterbox">
{project.map(project => (
<label className={`tag${project.type}`}>
<input
name="type"
type="checkbox"
key={project.id}
value={project.type}
onChange={handleChange}>
</input>
<span
className="tags">{project.type}
</span>
</label>
))}
</div>
<button className="info-button" onClick={() => toggleShow(!show)}>Info</button>
</div>
);
};
Solution 1:[1]
This might help
onInit={() => if (typeof window !== 'undefined') window.dispatchEvent(new Event('resize'))}
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 | Reasat Rafio |
