Carousel in React

React Carousel is a slideshow component for cycling by elements ? slides of pictures or text ? like a carousel.

How does it work?

React Carousel is a slideshow inside a bunch of content. It launches many images, text, or HTML elements and supports previous/next buttons.

The Page Visibility API is cross-browser compatible and prevents carousel scrolling when the user is not viewing a webpage (such as when the browser tab is inactive, the browser window is minimized, etc.).

It is a powerful, lightweight and fully customizable carousel component for React applications.

Installing as a package

Usage

Props:

NameValueDescription
ariaLabelstringDefines the area-label attribute for the root carousel element. By excluding the attribute from the markup, the default is undefined.
axis'horizontal', 'vertical'Set the direction of the slider, 'Horizontal,' by default.
autoFocusbooleanFocus on the Carousel while rendering.
autoPlaybooleanAutomatically change slide based on interval prop.
centerModebooleanCenter the current item and set the width of the slide based on centerSlidePercentage.
centerSlidePercentagenumberSet the width percentage relative to the carousel width when centerMode is true.
dynamicHeightbooleanThe height of the objects will not be fixed.
emulateTouchbooleanEnables swipe right on non-touch screens when swipeable.
infiniteLoopbooleanGoing after the last item will go back to the first slide.
intervalnumberTo skip to the next item automatically, the interval in milliseconds when autoplay is true is 3000 by default.
labelsobjectApply region labels to a carousel with an object with LeftArrow, RightArrow, and Item properties.
onClickItemfunctionThe default is {left arrow: 'previous slide/item', right arrow: 'next slide/item', item: 'slide item'}.
onClickThumbfunctionA callback to handle a click event on the thumb receives the current index and item as arguments.
onChangefunctionThe callback gets the current index and item as arguments each time the selected item changes to handle.
onSwipeStartfunctionThe callback is handled when a touch event initiates the swipe as an argument.
onSwipeEndfunctionTo handle when the swipe is finished, the callback receives a touch event as an argument.
onSwipeMovefunctionThe callback is triggered on every movement while swiping, receiving a touch event as an argument.
preventMovementUntilSwipeScrollTolerancebooleanDo not let the carousel scroll until the user swipes to the value specified on SwipeScrollTolerance.
renderArrowPrevfunctionRender custom back arrow. Receives a click handler, a boolean indicating whether there is a previous item, and an accessibility label as an argument.
renderArrowNextfunctionRender custom back arrow. Receives a click handler, a boolean indicating where the following item is, and an accessibility label as an argument.
renderIndicatorfunctionCurrent custom indicator. Receives a click handler, a boolean indicating whether the item is selected, the item index, and an accessibility label as arguments.
renderItemfunctionSubmit a custom item. Get an item from the Carousel and an object with the selected property as an argument.
renderThumbsfunctionRender prop to show thumb, receives carousel item as argument. Get the image tag of each item of the slider, and render it by default.
selectedItemnumberSet the selected item, default to 0.
showArrowsbooleanEnable Previous and Next arrows, True by default.
showStatusbooleanEnable the current item's absolute position, which is confirmed by default
showIndicatorsbooleanEnable the indicator to select an item, which defaults to true.
showThumbsbooleanEnable thumbs, defaults to true.
statusFormatterfunctionFormatter that returns the position as a string gets the current item and takes the total count as an argument. Defaults to {currentItem} of the format {total}.
stopOnHoverbooleanThe slide cannot change by autoplay on hover. Default to true.
swipeablebooleanEnable the user to swipe the Carousel, which defaults to true.
swipeScrollTolerancenumberThe number of pixels needed to slide a slide is five by default when swiping.
thumbWidthnumberThumb width, 80 by default.
transitionTimenumberThe duration of the slide change animation.
useKeyboardArrowsbooleanEnable arrows to move the slider when focused.
verticalSwipe'natural', 'standard'Set swipe mode when the axis is 'vertical.' The default is 'Standard.'
widthnumber or stringThe width of the Carousel is 100% by default.

Customizing

Items (Slides)

By default, each slide is rendered as passed as children. If we need to customize it, use the prop renderItem.

Thumbs

By default, thumbs are generated by extracting images in each slide. If you don't have pictures on your slides or prefer a different thumbnail, use the renderThumb method to return a new list of images to be used as thumbnails.

Arrows

By default, simple arrows are provided on each side. If you need to customize them and css isn't enough, use renderArrowPrev and renderArrowNext. The click handler is passed as an argument to the prop and must be added to the custom arrow as the click handler.

Indicators

By default, the indicators will be presented as those tiny little dots at the bottom of the carousel. To customize them, use the RenderIndicator prop.

Take full control of the carousel

If none of the previous options suffice, you can create your controls for the Carousel.

Custom Animations

By default, Carousel uses traditional 'slide' style animations. There is also a built-in fade animation, which is used by passing 'fade' to the AnimationHandler prop.

*Note: The 'fade' animation may not support swiping animations, so you may want to set swipeable to false.

If you want something completely custom, you can pass custom animation handler functions to AnimationHandler, SwipeAnimationHandler, and StopSwipingHandler. Animation handler functions accept props and positions and return the styles for the list, the default slide style, the selected slide style, and the previous slide style. Take a look at the fade animation handlers to get an idea of how they work:

Videos

If your Carousel is about videos, keep in mind that it's up to you to decide which videos are playing. Using the RenderItem prop, you will get information saying whether the slide is selected or not and can use this to change the position of the video.

React Carousel component

Carousel doesn't automatically normalize slide dimensions, and you may want to use additional utilities or custom methods to size content properly. While Carousel supports previous/following controls and indicators, they are not expected. Add and customize as you see fit.

Slides only

Carousel in React

With controls

It will add in the previous and next controls by controls property.

Carousel in React

With indicators

You can also attach the indicators to the Carousel lengthwise and the controls.

Carousel in React

With captions

Carousel in React

You can add captions to slides in any <CCarouselItem> with the <CCarouselCaption> element. Optional display utilities can be quickly hidden on a small viewport, as shown below. We hide them with .d-none and pull them back on medium-sized devices with .d-MD-block.

Some representative placeholder content for the first slide.

Crossfade

the carousel to animate slides with a fade transition instead of a slide.

Dark variant

Add a dark property to the CCrocell for dark color controls, indicators, and captions. Controls with the Filter CSS property are reversed from their default white fill, and captions and controls have additional Sass variables that customize the color and background color.

Some representative placeholder content for the first slide.

API

CCarousel


PropertyDescriptionTypeDefault
activeIndexIndex of the active object.number0
classNameA string of all the classnames you want to apply to the parent component.string-
controlsAdding to previous and next controls.boolean-
darkAdd darker controls, indicators, and captions.boolean-
indicatorsAdding indicators at the bottom of the Carousel for each item.boolean-
intervalThe amount of time for the delay between automatically cycling an item. If false, the Carousel will not cycle automatically.number | boolean5000
onSlidThe callback is fired when a slide transition is finished.(active: number, direction: string) => void-
onSlideThe callback is fired when a slide transition is initiated.(active: number, direction: string) => void-
pauseIf set to 'hover,' pauses cycling of the Carousel on mouseenter and resumes cycling of the Carousel on mouseleave. If set to false, hovering over the Carousel will not stop it.boolean | 'hover.'hover
transitionSet the transition type.'slide' | 'crossfade'-
wrapSet whether the Carousel must be cycled continuously or have a hard stop.booleantrue

CCarouselCaption


PropertyDescriptionTypeDefault
classNameA string of all the className we want to apply to the base component.string-

CCarouselItem


PropertyDescriptionTypeDefault
classNameA string of all the class names you want to apply to the parent component.string-
intervalThe amount of time for the delay between automatically cycling an item.number | booleanfalse

React-Bootstrap Carousel Component

React-Bootstrap is a front-end framework that was designed with React in mind. The Carousel component provides a way to create a slideshow for images or text slides in a cyclic manner for full rendering.

We use the following approach in ReactJS to use the react-bootstrap carousel component.

Carousel props:

  • Active Index: Used to control the currently active view slide. It is used as a custom element type for the component.
  • Controls: These display the Next/Prev buttons in the Carousel.
  • Default Active Index: This is the default Active Index which is 0.
  • Fade: Used to add fade animations between slides as they move.
  • Indicators: Used to display a set of slide status indicators.
  • Interval: Used to delay the time between cycles automatically.
  • Keyboard: Specifies whether the Carousel should respond to keyboard events.
  • Next icon: This is used to override the default next icon.
  • Next Label: This can show the next element in the Carousel and is a type of label shown only to screen readers.
  • On selection: This is a callback triggered when the active item changes.
  • onSlide: This callback is triggered when the slide transition ends.
  • onSlide: This callback is triggered when the slide transition begins. Pause is used to pause the slide based on different mouse events.
  • prevIcon: This is used to override the default last icon.
  • prevLabel: This can show the last element in the Carousel and is a type of label shown only to screen readers.
  • Ref: It is used to provide the attribute for the element.
  • Slides: This is used to enable animation between slides.
  • Touch: Touchscreen devices use a touchscreen to indicate whether they should support left/proper swipe interaction.
  • Wrap: Indicates whether the Carousel should be a continuous rigid stop or circle.
  • bsPrefix: This is an escape hatch to work with strongly optimized Bootstrap CSS.
  • Carousel. Item props: It will be used as the custom element type of the component.
  • Interval: This is used to delay the time between cycling for these items automatically.
  • bsPrefix: This is an escape hatch to work with strongly optimized Bootstrap CSS.
  • Carousel. Caption props: It is used as a custom element type for this component.
  • bsPrefix: This is the escape hatch for working with strongly optimized Bootstrap CSS.

Creating React App and installing module:

Step 1: Create a React application by using the below command:

Step 2:After creating the project folder, i.e., folder name, go to using the fcommand below:

Step 3: After creating the ReactJS application, install the required modules using the command below:

Project Structure: It looks like the below.

Carousel in React

Project Structure

Example: Now, write the below code in the App.js file. Here, App is the default component where we wrote our code.

App.js

Steps to run the application: Run the applications by using the command from the root directory of the project:

Output: Open the browser and go to http://localhost:3000/. You will see the following output:

Carousel in React
Next TopicReact-Paginate




Latest Courses