How to create an image carousel from React

Chay Auker
2 min readJun 24, 2021

--

I recently learned how to create an image carousel in React. It is also possible to do using react-ing-carousel . This is a very useful skill for displaying pictures in a variety of settings and for multiple purposes.

  1. I created an Images component and passed imagesArray as props which can be seen as follows:

2. I passed props and used map function to iterate all images and then used useState and set currentIndex = 0. I then created “Previous” and “Next” buttons. Results were as follows:

3. I then set the logic for handleClickPrev and handleClickNext buttons for when the user clicks and changes pictures as follows:

4. This allows the buttons to function when clicking through the pictures. However, there is no mechanism at this point to allow for a complete cycle when clicking the “previous” button on the first picture or the “next” button on the last picture. To fix this problem I set the condition as follows:

When scrolling forward through the pictures using the “next” button we get to the last picture and must setCurrentIndex to the first picture. When scrolling back through the pictures using the “previous” button we get to the first picture and must setCurrentIndex to the last picture. This allows for a complete uninterrupted cycle through the pictures.

I hope this was helpful and you are now able to construct a functional and efficient image carousel!

--

--

Chay Auker
Chay Auker

Written by Chay Auker

Software Engineering at Flatiron

No responses yet