🎥 react image slider
When building my wife's photography website, photogarropy, I knew I wanted the home page to prominently feature her work, so I made an image slider and placed it on the landing page of the site. I'll walk you through how to build it below.
First thing's first, our component will accept a list of images as props, and track the currently displayed image as state. If the snippet below looks a little odd to you, note that I'm using class properties, which I highly recommend.
Next we need to actually render an image in the slider. Use a CSS background-image
property so you can render the image. You should also create a reference to this element to use later when we modify what image is displayed.
In order to actually trigger the image change, use the componentDidMount
lifecycle method to set an interval. In the code below, I'm calling the changeImage
method every five seconds. Don't forget to clear the interval when the component unmounts!
Now it's time to write the core method for our slider component. Create a changeImage
method that grabs the carousel reference, increments the index, and sets the new image. Be sure to take into account wrapping after the last image!
In my use case, I had one final thing to consider. The website was meant to showcase my wife's photography, so I expected the images to be high quality. To ensure smooth carousel transitions, I preloaded the images when the component mounted.
And that's it! Check out the full slider source code and see it in action on the photogarropy site.
Tweet me your sliders @bradgarropy!