Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@whisperlab/nuka-carousel

whisperlab46MIT4.6.5TypeScript support: included

Pure React Carousel

react, carousel, nuka

readme

Maintenance Status

nuka-carousel

A Pure ReactJS Carousel Component

Maintained by Sarah Egan

Nuka Carousel Animated Example

Install

To add nuka-carousel to your project run the following command in your project folder.

$ yarn add @whisperlab/nuka-carousel

Example

import React from 'react';
import Carousel from '@whisperlab/nuka-carousel';

export default class extends React.Component {
  render() {
    return (
      <Carousel>
        <img src="https://via.placeholder.com/400/ffffff/c0392b/&text=slide1" />
        <img src="https://via.placeholder.com/400/ffffff/c0392b/&text=slide2" />
        <img src="https://via.placeholder.com/400/ffffff/c0392b/&text=slide3" />
        <img src="https://via.placeholder.com/400/ffffff/c0392b/&text=slide4" />
        <img src="https://via.placeholder.com/400/ffffff/c0392b/&text=slide5" />
        <img src="https://via.placeholder.com/400/ffffff/c0392b/&text=slide6" />
      </Carousel>
    );
  }
}

Running demo locally

The demo can be launched on your local machine via webpack-dev-server. Make sure you are running node version 9.11 or earlier. Once you have cloned this repo locally, run the following:

yarn
yarn build
yarn start

You can access the application on your localhost at the following url: Local Demo

Or on CodeSandBox at the following url: CodeSandBox Demo

Keyboard Controls

Key Combination Function
Right/Up Arrow or D/W key Next slide
Left/Down Arrow or A/S key Previous slide
Q key First slide
E key Last slide
SpaceBar When autoplay={true} pauses and unpauses carousel
  • Keyboard shortcuts are disabled as a default. To enable them set enableKeyboardControls prop to true.
  • keyCodeConfig prop can be used to configure the default keyCodes

Props

Name PropType Description Default
afterSlide React.PropTypes.func Hook to be called after a slide is changed.
animation React.PropTypes.oneOf(['zoom']) Adds a zoom effect on the currently visible slide. A transform: scale(0.85) is set as default, however, the scale can be customized using zoomScale prop. Property is applied on all slides except the current 1. Use cellAlign to align the slide with zoom effect where you'd like.
autoGenerateStyleTag React.PropTypes.bool When set to true, it will generate a style tag to help ensure images are displayed properly. Set to false if you don't want or need the style tag generated. true
autoplay React.PropTypes.bool Autoplay mode active. false
autoplayInterval React.PropTypes.number Interval for autoplay iteration. 3000 milliseconds
autoplayReverse React.PropTypes.bool Only meaningful when autoplay is already true. When autoplayReverse is also true, autorotation cycles through slides indexes from high to low. false
beforeSlide React.PropTypes.func Hook to be called before a slide is changed
cellAlign React.PropTypes.oneOf(['left', 'center', 'right']) When displaying more than one slide, sets which position to anchor the current slide to. Is overridden to left when transitionMode="fade"
cellSpacing React.PropTypes.number Space between slides, as an integer, but reflected as px
enableKeyboardControls React.PropTypes.bool When set to true will enable keyboard controls. false
keyCodeConfig PropTypes.exact({ previousSlide: PropTypes.arrayOf(PropTypes.number), nextSlide: PropTypes.arrayOf(PropTypes.number), firstSlide: PropTypes.arrayOf(PropTypes.number), lastSlide: PropTypes.arrayOf(PropTypes.number), pause: PropTypes.arrayOf(PropTypes.number) }) If enableKeyboardControls prop is true, you can pass configuration for the keyCode so you can override the default keyboard keys configured. { nextSlide: [39, 68, 38, 87], previousSlide: [37, 65, 40, 83], firstSlide: [81], lastSlide: [69], pause: [32] }
disableAnimation React.PropTypes.bool When set to true, will disable animation. false
disableEdgeSwiping React.PropTypes.bool When set to true, will disable swiping before first slide and after last slide. false
dragging React.PropTypes.bool Enable mouse swipe/dragging. true
easing React.PropTypes.string Animation easing function. See valid easings here: D3 Easing Functions
edgeEasing React.PropTypes.string Animation easing function when swipe exceeds edge. See valid easings here: D3 Easing Functions
frameOverflow React.PropTypes.string Used to set overflow style property on slider frame. hidden
framePadding React.PropTypes.string Used to set the margin of the slider frame. Accepts any string dimension value such as "0px 20px" or "500px"
heightMode React.PropTypes.oneOf(['first', 'current', 'max']) Change the height of the slides based either on the first slide, the current slide, or the maximum height of all slides. Overrides height set by initialSlideHeight
initialSlideHeight React.PropTypes.number Initial height of the slides in pixels. 100
initialSlideWidth React.PropTypes.number Initial width of the slides in pixels
pauseOnHover React.PropTypes.bool Pause autoPlay when mouse is over carousel. true
renderAnnounceSlideMessage React.PropTypes.func Renders message in the ARIA live region that is announcing the current slide on slide change Render function that returns "Slide {currentSlide + 1} of {slideCount}"
slideIndex React.PropTypes.number Manually set the index of the slide to be shown
slideOffset React.PropTypes.number While using prop animation = "zoom", you can configure space around current slide with slideOffset. 25
slidesToScroll React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.oneOf(['auto'])]) Slides to scroll at once. Set to "auto" to always scroll the current number of visible slides. Is overridden to slidesToShow when transitionMode="fade"
slidesToShow React.PropTypes.number Number of slides to show at once. Will be cast to an integer when transitionMode="fade"
slideWidth React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number]) Manually set slideWidth. If you want hard pixel widths, use a string like slideWidth="20px", and if you prefer a percentage of the container, use a decimal integer like slideWidth={0.8}
speed React.PropTypes.number Animation duration/Transition speed in milliseconds
swiping React.PropTypes.bool Enable touch swipe/dragging true
transitionMode React.PropTypes.oneOf(['scroll', 'fade', 'scroll3d']) Set the way slides transition from one to the next. scroll
vertical React.PropTypes.bool Enable the slides to transition vertically
width React.PropTypes.string Used to hardcode the slider width. Accepts any string dimension value such as "80%" or "500px"
withoutControls React.PropTypes.bool Used to remove all controls at once. Overwrites the render[Top, Right, Bottom, Left]CenterControls(). false
wrapAround React.PropTypes.bool Sets infinite wrapAround mode. false
zoomScale React.PropTypes.number Adds a number value to set the scale of zoom when animation === "zoom". The number value should be set in a range of (0,1). The default value is set to zoomScale: 0.85
opacityScale React.PropTypes.number Adds a number value to set the scale of the opacity for the 'scroll3d' transition mode. The number value should be set in a range of (0,1). The default value is set to opacityScale: 0.65
onDragStart React.PropTypes.func Adds a callback to capture event at the start of swiping/dragging slides

render*Controls

React.PropTypes.func

A set of eight render props for rendering controls in different positions around the carousel.

  • Valid render props for the eight positions are renderTopLeftControls, renderTopCenterControls, renderTopRightControls, renderCenterLeftControls, renderCenterCenterControls, renderCenterRightControls, renderBottomLeftControls, renderBottomCenterControls, and renderBottomRightControls.

  • The default props are set as renderCenterLeftControls for Previous button, renderCenterRightControls for the Next button and renderBottomCenterControls for the "Paging dots". To change the position or remove "Paging dots", the default positions need to be disabled by setting them to null.

<Carousel
  renderTopCenterControls={({ currentSlide }) => (
    <div>Slide: {currentSlide}</div>
  )}
  renderCenterLeftControls={({ previousSlide }) => (
    <button onClick={previousSlide}>Previous</button>
  )}
  renderCenterRightControls={({ nextSlide }) => (
    <button onClick={nextSlide}>Next</button>
  )}
>
  {/* Carousel Content */}
</Carousel>
  • The function returns the props for goToSlide, nextSlide and previousSlide functions in addition to slideCount and currentSlide values. Can also remove all render controls using withoutControls.

  • NOTE: The className slide-visible is added to the currently visible slide.

renderAnnounceSlideMessage

React.PropTypes.func

renderAnnounceSlideMessage render prop is a special case of the render*Controls props. It's responsibility is to render ARIA live announcement message to improve accessibility. The prop will announce the message you pass in every time the slide changes with VoiceOver enabled on your machine. The function returns only slideCount and currentSlide values.

<Carousel
  renderAnnounceSlideMessage={({ currentSlide, slideCount }) =>
    `Slide ${currentSlide + 1} of ${slideCount}`
  }
>
  {/* Carousel Content */}
</Carousel>

You can control the state of the carousel from your parent component as shown below:

import React from 'react';
import Carousel from '@whisperlab/nuka-carousel';

export default class extends React.Component {
  state = {
    slideIndex: 0
  };

  render() {
    return (
      <Carousel
        slideIndex={this.state.slideIndex}
        afterSlide={slideIndex => this.setState({ slideIndex })}
      >
        <img src="https://via.placeholder.com/400/ffffff/c0392b/&text=slide1" />
        <img src="https://via.placeholder.com/400/ffffff/c0392b/&text=slide2" />
        <img src="https://via.placeholder.com/400/ffffff/c0392b/&text=slide3" />
        <img src="https://via.placeholder.com/400/ffffff/c0392b/&text=slide4" />
        <img src="https://via.placeholder.com/400/ffffff/c0392b/&text=slide5" />
        <img src="https://via.placeholder.com/400/ffffff/c0392b/&text=slide6" />
      </Carousel>
    );
  }
}

TypeScript

TypeScript type definitions are now shipped with nuka-carousel. You can use them directly from the library.

Resizing Height

How resizing works

In componentDidMount, the initial dimensions are assigned to each slide:

  • Width: initialSlidewidth || slideWidth || (slidesToShow / width of container)
  • Height: initialSlideHeight

After the component completes mounting with the accurate width, it tries to calculate the desired height of the content (current, first, max). If that calculation fails (perhaps because slide images are still loading), it'll wait a bit and try again. Once successful, that measurement then replaces initialSlideHeight with the measured height in pixels.

Contributing

See the Contribution Docs.

Maintenance Status

Active: Formidable is actively working on this project, and we expect to continue for work for the foreseeable future. Bug reports, feature requests and pull requests are welcome.

changelog

Nuka Changelog

4.6.0 (2019-12-17)

  • Fixes for leftAlign added for heightMode="current" and heightMode="max"
  • #614 Remove getListItemStyles() from type definitions
  • #619 Configure keyboard keyCodes so default ones can be overridden
  • #620 Avoid redundant dimension calculations after a DOM mutation
  • #621 Add TS definition for renderAnnounceSlideMessage
  • #625 Fixes Issue 521: Initial height calculations will be repeated until successful.
  • #626 Height mode 'current' uses tallest visible slide
  • #628 Adding missing Type For keyCodeConfig prop

4.5.13 (2019-11-08)

  • #592 change componentWillReceiveProps to UNSAFE_componentWillReceiveProps
  • #600 Fix wraparound logic to account for cellAlign property
  • #601 Change dot styling
  • #608 Fix dragging issue in Safari
  • #609 Prevent scroll when dragging on iOS

4.5.12 (2019-09-13)

  • #582 Another attempt to fix the height issue by changing the default prop value for height
  • #584 Fix multi-slide wraparound
  • #585 Fix onDragStart, should only happen with dragging/swiping
  • #588 Impossible to select last images when swiping, this fixes that

4.5.11 (2019-09-03)

  • #578 update vulnerable deps, fix broken scroll animation
  • #576 Clear timeouts when component unmounts to prevent memory leak

4.5.10 (2019-09-02)

  • #574 Add event param to onDragStart method
  • #573 Fix resizing height issue due to dynamically loaded elements and readyStateChange issues
  • #572 Fix Travis configuration
  • #571 Next and Previous buttons should not be submit type buttons
  • #565 Add missing controls to the TypeScript library definition
  • #564 Export NextButton, PreviousButton, PagingDots from main entry point to allow for easier style targeting
  • #562 Allow isEdgeSwiping to work with vertical slider
  • #561 Avoid the empty div wrapper for null custom controls

4.5.9 (2019-07-09)

  • #557 Add type for animation prop
  • #555 Fix wrongly calculated height for the current slide on slide change

4.5.8 (2019-05-23)

  • #551 Add disableEdgeSwiping prop to disable white space on last and first slide when swiping
  • #549 Add type=button to paging dots

4.5.5 (2019-05-07)

  • #545 Add onDragStart to index.d.ts
  • #541 Adds scroll3d to types
  • #536 Add type definition for PagingDots class
  • #535 Allow null to be passed to render controls

4.5.4 (2019-04-15)

  • #517 Fix bug when changing to vertical mode, add missing prop to types
  • #524 Remove extra function wrap around handleMouse methods
  • #525 Fix calculation of dimensions
  • #526 Add classnames to paging dots to improve styling ability
  • #529 Fix IE11 error related to #525
  • #532 Update README.md with OSS status

4.5.3 (2019-03-18)

  • Resolve dependency vulnerabilities
  • #506 Add Scroll3D transition mode option

4.5.2 (2019-03-08)

  • Fixes dragging bug

4.5.1 (2019-03-06)

  • #511 Adds style and transitionMode types
  • #510 Adds new prop to allow autoplay in reverse

4.4.9 (2019-03-04)

  • #508 Fix speed slide flicker/blinking

4.4.8 (2019-02-21)

  • #501 Add cellAlign type to CarouselSlideRenderControlProps interface
  • #500 Animation performance enhancements
  • #496 Upgrade react-move
  • #492 Fix Paging Dots sync, fix 'Next' button validation
  • #490 Disable animation for an initial slide when non-default slideIndex prop is passed
  • #489 Disable animation prop created
  • #488 Configurable zoom scale prop
  • #487 updates to README

4.4.7 (2019-01-21)

  • #480 Add Types to build
  • #486 Fix mouse event handling to account for click events within the slide

4.4.6 (2019-01-12)

  • #477 Add TypeScript types
  • #475 Fix click event handler on button within slide element
  • #473 Add zoom effect prop

4.4.5 (2018-12-31)

  • #469 Fix initial height issue

4.4.4 (2018-12-07)

  • #460 Ability to configure aria-live message with prop
  • #458 Fix flicker in wrap-around
  • #453 Fix issue involving updating props on beforeSlide

4.4.3 (2018-11-16)

  • #451 Allow clicks with modifier present
  • #446 Fix for demo (toggle between 2 and 6 slides showing)
  • #445 Add disableKeyboardControls prop to allow users to disable keyboard controls
  • #441 Start work on removing deprecated lifecycle methods
  • #439 Allow pauseOnHover to work when swiping/dragging is disabled
  • #436 Refactoring

4.4.2 (2018-10-29)

  • #425 Accessibility features added

  • Adding keyboard controls

  • Reader lets you know what slide you are on
  • Slide that is being display will be read by reader

  • #435 Fix issues where clickDisabled is set to true too often

  • #433 add function to add ariaProps to all visible slides
  • #432 Add slide-visible class to all currently visible slides
  • #431 Carousel would go into an infinite loop between two slide. Added a isTransitioning check to wait until afterSlide is finish.

4.4.1 (2018-10-08)

  • #423 Prevent click events only when swiping