DEV Community

Cover image for Building a simple slideshow component in React using Hooks
Kenneth Lum
Kenneth Lum

Posted on

Building a simple slideshow component in React using Hooks

I was trying to build a simple slideshow component using React Hooks. Initially, I was thinking of how to use calculations to position a picture properly on the page or inside of the component region.

It turns out it is a lot simpler, if we use containers or containers that cover the whole viewport to contain a picture, and move the container accordingly.

The reason is, if we calculate where to place the image, and what size to use, it can be a lot of calculations. If we use a container and set the max-width and max-height, and we center the picture in the container, such as by using the container as a flex box, then we don't have to do all the calculations and it is automatically handled by CSS.

In the example here, I am trying to use the viewport, and to better use it using CSS, note that we can use the unit of vw and vh, which is viewport width and viewport height.

I "dock" the containers at the left of the screen (hidden):

  function theLeftShift(i) {
    if (currentImageIndex === i) return 0;
    else if (i > currentImageIndex) return "100vw";
    else return "-100vw";
Enter fullscreen mode Exit fullscreen mode


        {Array.from({ length: nImages }, (e, i) => i + 1).map((e, i) => (
          <li style={{ left: theLeftShift(i) }}>
            <img src={`./pic${e}.jpg`} />
Enter fullscreen mode Exit fullscreen mode

We don't really need to move the containers further and further left, and can just dock it to the immediate left. That way, we don't need to create a region that is wider than it is needed.

The demo:

The full page demo:

Top comments (0)