I am trying to create a carousel in nextjs with what I consume from an api and for that I am using glider-js. The problem is that the div that glinder-js creates does not contain the elements that I render when consuming an api.
This is the rendering code of the elements that I have
JavaScript
x
23
23
1
<div className="glider" >
2
<div className="glider__contain" >
3
<button className="glider__prev" aria-label="Previous" >
4
<FontAwesomeIcon icon={faChevronLeft} style={{ width: '20px' }} />
5
</button>
6
<div className="glider__list">
7
{
8
today.map(el =>
9
<div key={el.mal_id} className="glider__element" >
10
<img src={el.image_url} alt={el.title} />
11
<p>{el.title}</p>
12
</div>
13
)
14
}
15
</div>
16
<button className="glider__next" aria-label="Next" >
17
<FontAwesomeIcon icon={faChevronRight} style={{ width: '20px' }} />
18
</button>
19
<Carrousel />
20
</div>
21
<div role="tablist" className="glider__dots" ></div>
22
</div>
23
And the code of the glinder-js function is the following
JavaScript
1
20
20
1
export default function Carrousel() {
2
3
useEffect(() => {
4
window.addEventListener('load', function (e) {
5
console.log(document.querySelector('.glider__list'))
6
new Glider(document.querySelector('.glider__list'), {
7
slidesToShow: 5,
8
slidesToScroll: 5,
9
draggable: true,
10
dots: '.glider__dots',
11
arrows: {
12
prev: '.glider__prev',
13
next: '.glider__next'
14
},
15
})
16
})
17
}, [])
18
19
return null}
20
this is what I get in the elements already rendered
Advertisement
Answer
Your load event is likely before Next rendered, try referencing the element instead.
You will also likely need to ensure you API has returned the required data prior to mounting.
Lastly, you will need to cleanup the glider instance on unmount. It has a lot of event listeners that will cause a memory leak if they are not removed on unmount.
JavaScript
1
27
27
1
export const Carrousel = () => {
2
const gliderListRef = useRef(null);
3
4
useEffect(() => {
5
let glider;
6
//if ref.current is set - next has mounted & today data is set
7
if (gliderListRef.current) {
8
glider = new Glider(gliderListRef.current, {
9
your_options
10
});
11
}
12
return () => {
13
// cleanup listeners on unmount
14
if(glider) glider.destroy();
15
}
16
}, []);
17
18
//ensure the API returned required data prior to setting ref
19
if(!!!today.length) return 'loading...';
20
21
return (
22
<div className="glider">
23
<div className="glider__list" ref={gliderListRef}></div>
24
</div>
25
);
26
};
27