The Ultimate ReactJS Image Slider | Phase 1

anobjectisa

an-object-is-a

Posted on December 10, 2020

The Ultimate ReactJS Image Slider | Phase 1

ReactJS Image Slider - Laying down the foundation.


This is Phase One of a Two-phase project where we build a fully responsive image slider for mobile and desktop.

Phase Two is coming soon.


Browse our Teachable courses.


Ultimate ReactJS Image Carousel

We'll start by putting all of our elements on screen.

We need two components: Deck.js and Card.js

We have 7 elements to work with:

  • In the Deck.js
  • a button for moving right (BUTTON)
  • a button for moving left (BUTTON)
  • a view port (DIV)
  • an images container (DIV)
  • a touch area that we'll use to determine whether or not the user is allowed to scroll the carousel (DIV)
  • In the Card.js
  • a "card" which we'll use to hold the image (DIV)
  • the actual image (IMG)

elements on screen no css

Now we need to center everything on screen.

We'll use a combination of absolute positions and transforms.
elements on screen centered

Now that everything is centered, we need to order the cards from left to right.

We write a simple function that determines the middle card of our deck and moves the cards to the left of that middle to the left and the cards to the right of that middle to the right.
elements on screen ordered


Let's discuss RESPONSIVE.

To make our carousel responsive, we need to resize our view port based on percentages and not hard pixel units.

So we'll just pick 50% and calculate a hard pixel count based on the width of the user's browser window; then we'll run this code in a resize window event listener.

window.addEventListener('resize', () => {
    img_width_as_percentage = 50;
    // img_width_as_percentage = window.innerWidth < 768 ? 100 : img_width_as_percentage;

    this.new_width =
        /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ?
            (img_width_as_percentage / 100) * window.screen.width :
            (img_width_as_percentage / 100) * window.innerWidth;

    this.view_port.style.width = `${this.new_width}px`;

    this.order_cards();
});
Enter fullscreen mode Exit fullscreen mode
Now that we have our resize code, every time we resize the browser window, our carousel resizes.

elements on screen responsive


We have our elements laid out and ready to go.

You can get the source files here.

In the next phase, we'll start moving this thing with touch, button, and wheel navigation.


If you want a more in-depth guide, check out my full video tutorial on YouTube, An Object Is A.

How to Create The ULTIMATE Image Slider in ReactJS | Phase 1

💖 💪 🙅 🚩
anobjectisa
an-object-is-a

Posted on December 10, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

The Ultimate ReactJS Image Slider | Phase 1
programming The Ultimate ReactJS Image Slider | Phase 1

December 10, 2020