Skip to content

They don’t load the elements inside the div that glider-js creates in nextjs

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

<div className="glider" >
        <div className="glider__contain" >
            <button className="glider__prev" aria-label="Previous" >
                <FontAwesomeIcon icon={faChevronLeft} style={{ width: '20px' }} />
            <div className="glider__list">
                        <div key={el.mal_id} className="glider__element" >
                            <img src={el.image_url} alt={el.title} />
            <button className="glider__next" aria-label="Next" >
                <FontAwesomeIcon icon={faChevronRight} style={{ width: '20px' }} />
             <Carrousel />
        <div role="tablist" className="glider__dots" ></div>

And the code of the glinder-js function is the following

export default function Carrousel() {

useEffect(() => {
    window.addEventListener('load', function (e) {
        new Glider(document.querySelector('.glider__list'), {
            slidesToShow: 5,
            slidesToScroll: 5,
            draggable: true,
            dots: '.glider__dots',
            arrows: {
                prev: '.glider__prev',
                next: '.glider__next'
}, [])

return null}

this is what I get in the elements already rendered


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.

export const Carrousel = () => {
  const gliderListRef = useRef(null);

  useEffect(() => {
    let glider;
    //if ref.current is set - next has mounted & today data is set
    if (gliderListRef.current) {
      glider = new Glider(gliderListRef.current, {
    return () => {
     // cleanup listeners on unmount
     if(glider) glider.destroy();
  }, []);

  //ensure the API returned required data prior to setting ref
  if(!!!today.length) return 'loading...';

  return (
    <div className="glider">
      <div className="glider__list" ref={gliderListRef}></div>