I used react-simple-image-slider for image slider on my website, but after i resize the browser window the application gets stucked.
The main Aim is to make the react-simple-image-slider responsive.
The below is the code.
JavaScript
x
47
47
1
import './App.css';
2
import {useLayoutEffect, useState } from 'react';
3
import SimpleImageSlider from 'react-simple-image-slider';
4
5
function App() {
6
const [widthAndHeight, setwidthAndHeight] = useState([window.innerWidth, 600]);
7
8
useLayoutEffect ( ()=>
9
{
10
function updateTheWidthAndHeight()
11
{
12
setwidthAndHeight([window.innerWidth, 600]);
13
14
}
15
window.addEventListener('resize', ()=>{
16
updateTheWidthAndHeight();
17
})
18
})
19
20
const images = [
21
{ url: "logos/ethiopia.png" },
22
{ url: "logos/favicon.ico" },
23
{ url: "logos/gear.png" },
24
{ url: "logos/gear.jpg" }
25
];
26
27
28
return (
29
<div>
30
<SimpleImageSlider
31
style={{ margin: '0 auto', marginTop: '0px'}}
32
className="slider"
33
width={widthAndHeight[0]}
34
height={widthAndHeight[1]}
35
slideDuration={1}
36
loop={true}
37
autoPlay={true}
38
images={images}
39
showBullets={false}
40
showNavs={true}
41
/>
42
</div>
43
);
44
}
45
46
export default App;
47
Advertisement
Answer
You forgot a dependency list for useLayoutEffect
so it’s adding an event listener on every render. Add an empty list for one-time execution:
JavaScript
1
9
1
useLayoutEffect(() => {
2
function updateTheWidthAndHeight() {
3
setwidthAndHeight([window.innerWidth, 600]);
4
}
5
window.addEventListener("resize", () => {
6
updateTheWidthAndHeight();
7
});
8
}, []);
9