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' }} /> </button> <div className="glider__list"> { today.map(el => <div key={el.mal_id} className="glider__element" > <img src={el.image_url} alt={el.title} /> <p>{el.title}</p> </div> ) } </div> <button className="glider__next" aria-label="Next" > <FontAwesomeIcon icon={faChevronRight} style={{ width: '20px' }} /> </button> <Carrousel /> </div> <div role="tablist" className="glider__dots" ></div> </div>
And the code of the glinder-js function is the following
export default function Carrousel() { useEffect(() => { window.addEventListener('load', function (e) { console.log(document.querySelector('.glider__list')) 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
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.
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, { ...your_options }); } 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> </div> ); };