How to create a Responsive Carousel in React JS

You must be familiar with creating a responsive Carousel when using React JS. The options are always unique and establish a new thing for a series of images to work. It includes custom markup, text, and a series of images. It carries out supportive options and works with previous/next controls and indicators. Of course, you can hire React developers who are well-known for creating carousels in React JS.

Here, you can find lists of steps to explore and create a responsive carousel in React JS that benefits web development.

  • Understand the structure
  • Implement a simple carousel in React
  • Add some styling
  • Add the Carousel to the App
  • Configure the active item
  • Implement the indicators
  • Carousel/Slider with auto cycle
  • Pause/Resume the Carousel/Slider on mouse hover/mouse leave

Step 1: Recognize the structure

As you can see, Div. The inner will translate to display element #1. We can easily use the translateX property for the Div. Inner to adjust accordingly. If you want to show element number 1, Div. Inner will have transform: translateX(0%)

If element #2 is visible, the Div. Inner will have a transform: translateX(-100%)

And if Item #3 is visible, then Div.Inner will convert: translateX(-200%)

Step 2: Implement a simple carousel in React

I assume you understand React app development and how to set up a React app.

Let’s start by creating a Carousel.js with the following code:

	
import React from "react";
import "./Carousel.css";
export const CarouselItem = ({ children, width }) => {
return (
<div className="carousel-item" style={{ width: width }}>
{children}
</div>
);
};

const Carousel = ({ children }) => {
return (
<div className="carousel">
<div className="inner" style={{ transform: "translateX(-0%)" }}> 
{React.Children.map(children, (child, index) => {
return React.clone Element (child, { width: "100%" });
})}
</div>
</div>
);
};
export default Carousel;

We need to create two components: Carousel & CarouselItem

The Carousel component will be the main controller to control the items

The CarouselItem component will display the item itself. Now we need to pass the width property to this element.

It will create Carousel.css in the next step

Iterate over all child elements. This will be the CarouselItem component and adjust the width property. Now we will set the width to 100%. This means we will only have one element visible. This solution will allow us to control the lifecycle of React components of the Carousel component later. You can read more about React. Children. Map and React.cloneElement to understand.

Also Read: Parse CSV File by Using React JS

Step 3: Add Style

  • We need to hide overflow content inside, only showing active element
  • This line is extremely important so that our article is on 1 line; otherwise, it will default to a new line.
  • Added transition for Div. Inner, so it animates when the active element changes. The element’s type. You can do whatever you want here, but
  • make sure the screen is inline-flex or inline-block to keep them on 1 line.
	
.carousel{
    overflow: hidden;
}
.inner{
    white-space: nowrap;
    transition: transform 0.3s;
}
.carousel-item{
    display: inline-flex;
    align-items: center;
    justify-content: center;
    height: 200px;
    background-color: green;
    color: #fff;
}

Step 4: Add Carousel to App.js

Now we can see the first version of the component by adding it to App.js

	
import Carousel, { CarouselItem } from "./components/Carousel";


function App() {


  return (
    <div className="App">
      <Carousel>
        <CarouselItem>Item 1</CarouselItem>
        <CarouselItem>Item 2</CarouselItem>
        <CarouselItem>Item 3</CarouselItem>
      </Carousel>
    </div>
  );
}


export default App;

Step 5: Configure Active Item

Let’s see how we control the active item in the Carousel component. As I mentioned earlier, we will use translateX to move the Div. Inner to show the active element. Let’s see how translateX works in Carousel.js, and then we may have a solution. You can see that the active element is updated when the translated value is changed, so we need to implement logic to change this value. Let’s update our Carousel.js like this.

	
import React,{useState} from "react";


import "./Carousel.css";


export const CarouselItem = ({ children, width }) => {


    return (
        <div className="carousel-item" style={{ width: width }}>
            {children}
        </div>
    );


};


const Carousel = ({ children }) => {
    const [activeIndex,setActiveIndex]= useState(0)
    return (
        <div className="carousel">
            <div className="inner" style={{ transform: `translateX(-${activeIndex*100})` }}>
                {React.Children.map(children, (child, index) => {
                    return React.cloneElement(child, { width: "100%" });
                })}
            </div>
        </div>)
}


export default Carousel;

We need to manage the active state; we use the useState hook here. The key is the line 20 translateX(-${activeIndex * 100}%). Why do we use 100? Because we have 100% width for each item. For example, if we have two active elements (50% width for each) and we need to drag each element, the number should be 50 => 50%. Let’s find out the relationship between them:

  • 1 active element, width 100% => translateX(-${activeIndex * 100}%)
  • Two active elements, width 50% and slide one by one => translateX(-${activeIndex * 50}%)
  • 2 active elements, 50% width and sliding both => translateX(-${activeIndex * 100}%)

Step 6: Implement the Indicators

In the previous step, we finished the element logic working, but it still doesn’t work because we need control to trigger the update. We will have a method to update the new active index called update-index ().

	
import React,{useState} from "react";


import "./Carousel.css";


export const CarouselItem = ({ children, width }) => {


    return (
        <div className="carousel-item" style={{ width: width }}>
            {children}
        </div>
    );


};


const Carousel = ({ children }) => {
    const [activeIndex,setActiveIndex]= useState(0)


    const updateIndex =(newIndex)=>{
        if(newIndex < 0 ) {
            newIndex = 0
        }else if(newIndex >=React.Children.count(children)){
            newIndex =React.Children.count(children)-1
        }
        setActiveIndex(newIndex)
    }




    return (
        <div className="carousel">
            <div className="inner" style={{ transform: `translateX(-${activeIndex*100}%)` }}>
                {React.Children.map(children, (child, index) => {
                    return React.cloneElement(child, { width: "100%" });
                })}
            </div>


            <div className="indicators">
                <button
                  onClick={()=>{
                    updateIndex(activeIndex - 1)
                  }}
                >
                   Prev
                </button>
                <button
                  onClick={()=>{
                    updateIndex(activeIndex + 1)
                  }}
                >
                 Next
                </button>


            </div>




        </div>)
}


export default Carousel;

Step 7: Carousel/Slider with auto cycle

If the active element is the first, we will jump to the last element when the user clicks on the previous button. Our approach will use setInterval(). You can check how it works here. Since the conveyor belt is in an automatic cycle, it becomes an infinite carousel.

If the active element is the last, we will return to the first element when the user clicks the next button. Please review the update-index () method. We have a carousel that automatically rotates after a certain amount of time.

Also Read: How to Use Push Method In React Hooks?

Step 8: Pause/resume carousel/cursor when hovering over/leaving

Usually, the carousel will allow users to hover to stop scrolling, so they have more time to read the content. We can have it after this step. How to pause setInterval()? The API doesn’t help us do that.

My solution is to keep the interval running, but we can have a state to check if the user hovers over the carousel; we don’t need to trigger the update-index () method.

Step 9: Mobile swipeable carousel

Swiping is a must-have feature on a carousel, especially on a responsive web app. It can be done easily by this step. We can do it manually using onTouchStart and untouched, but I will use a library to reduce the complexity. This will provide us with easy-to-use event handlers. Let’s see how I apply it to our Carousel.js. So, it would be best if you noticed the swipeable carousel changes in the React JS value and set out a new thing forever.

	
 const [paused,setpaused]=useState(false)


    const updateIndex =(newIndex)=>{
        if(newIndex < 0 ) {
            newIndex = 0
        }else if(newIndex >=React.Children.count(children)){
            newIndex =React.Children.count(children)-1
        }
        setActiveIndex(newIndex)
    }
useEffect(()=>{
    const interval= setInterval(()=>{
        if(!paused){
            updateIndex(activeIndex +1)
        }
    },1000)


    return ()=>{
        if(interval){
            clearInterval(interval)
        }
    }
})


    return (
        <div
        className="carousel"
        onMouseEnter={()=>setpaused(true)}
        onMouseLeave={()=>setpaused(false)}
        >

Schedule an interview with React developers

Conclusion

Indeed, one can develop a responsive carousel in ReactJS development with the perfect steps. Here, we have learned all the right steps for a carousel component in React. While building the carousel component, React component libraries play a crucial role. As a leading mobile app development company, we deliver the best content, making your procedure smooth, fast, and flexible. You can share your queries, doubts, and suggestion in the comment section.

Feel free to get in touch with us!

Frequently Asked Questions (FAQs)

1. What is React responsive carousel?

React-Responsive-Carousel is the Javascript or React package used for frontend applications to view image or video galleries, sell products, and view related blogs. Hence, the carousel component develops the slideshow for the images or text slides in a presentable manner in a cyclic way.

2. What is the format of the carousel?

The carousel format will help you to view two or more images or videos in a single ad; each has its headline, description, call to action, and link. To scroll via the carousel, people swipe on their mobile devices or click the arrows on their computer screen.

3. How do you make the carousel accessible?

The major carousel accessibility consideration for sighted users is not to make it auto-play. If you must create the carousel auto-play, you must give the pause or stop button. If you use the pause o stop button, place the previous carousel, and provide the descriptive link just like the text, “Pause animated content”.


Book your appointment now

Get in touch






    Stay up-to-date with our blogs