Search code examples
javascriptastrojs

How to connect swiper js to astro.build and make it a component?


How to connect swiper js to astro.build and make it a component? Without using React


Solution

  • I managed to achieve that with a after the carousel element, not in the frontMatter but at the following of the code inside my component ProjectSlider.astro.
    The script should begin with these 4 lines which makes the SwiperJS slider registered and available.
    You can see it here in the Swiper Docs : https://swiperjs.com/element#install--register-from-npm
    Here is my example :

    ---
    // Your frontMatter here
    ---
    
    <!-- ProjectSlider.astro -->
    <section id="ProjectSlider" class="swiper">
        <ul class="swiper-wrapper" data-cursor="swipe">
            {
                slides.map((slide) => (
                    <li class="swiper-slide">
                        // Your Card here
                    </li>
                ))
            }
        </ul>
    </section>
    
    <script>
    
        import 'swiper/css';
        import Swiper from 'swiper';
        import { register } from 'swiper/element/bundle';
        register();
    
        const swiper = new Swiper('#ProjectSlider', {
            // Setup
            loop: false,
            lazy: true,
            autoplay: false,
            grabCursor: false,
            mousewheel: false,
        });
    
    </script>
    <!-- /ProjectSlider.astro -->