README
use-carousel-state
React hook managing the state of a carousel. A carousel is a slideshow for cycling through a series of slides (image, video, audio, text, etc.). You can:
- navigate backward/forward
- navigate to a specific slide
- play/pause the slideshow
Install
yarn add @gdo-bzh/use-carousel-state react-use react # github package registry
yarn add use-carousel-state react-use react # npmjs registry
# or
npm install --save @gdo-bzh/use-carousel-state react-use react # github package registry
npm install --save use-carousel-state react-use react # npmjs registry
Usage
import React from 'react'
import { useCarouselState } from 'use-carousel-state'
const slides= [..., {/* slide i */}, ..., {/* slide n */}]
const Example = () => {
const {
autoPlay,
currentIndex,
autoPlayInterval,
play,
pause,
previousSlide,
nextSlide,
gotoSlide,
} = useCarouselState({ slideCount:slides.length, autoPlayInterval:2500 });
return (
<div className="carousel">
<Section>
<PreviousSlideFab onClick={previousSlide} />
<NextSlideFab onClick={nextSlide} />
<PlayPauseFab playing={autoPlay} onToggle={autoPlay ? pause : play} />
<Slide src={slides[currentIndex]} title={`slide #${currentIndex}`} />
</Section>
{autoPlay && <Progress duration={autoPlayInterval / 1000} />}
<NavBar
slides={slides}
selectedIndex={currentIndex}
onSlideSelect={gotoSlide}
/>
</div>
)
}
A complete example is available under the example folder.
Api
type UseCarouselState = {
(initialState: Partial<State>, reducer?: CarouselReducer): {
currentIndex: State["currentIndex"];
autoPlay: State["autoPlay"];
autoPlayInterval: State["autoPlayInterval"];
play: () => void;
pause: () => void;
nextSlide: () => void;
previousSlide: () => void;
gotoSlide: (index: number) => void;
};
defaultReducer: CarouselReducer;
};
type CarouselReducer = React.Reducer<State, Action>;
type State = {
/**
* true to start an animated slideshow
*/
autoPlay: boolean;
/**
* The amount of time to delay between automatically cycling a slide
*/
autoPlayInterval: number;
/**
* true will make navigation cycling
*/
loop: boolean;
/**
* the number of slides to navigate at a time
*/
step: number;
/**
* current slide index
*/
currentIndex: number;
/**
* total slide count
*/
totalSlideCount: number;
};
enum ActionType {
/**
* navigate to previous slide
*/
PREVIOUS,
/**
* navigate to next slide
*/
NEXT,
/**
* navigate to specific slide
*/
GOTO,
/**
* start slideshow
*/
PLAY,
/**
* pause slideshow
*/
PAUSE,
}
type Action =
| {
type:
| ActionType.PREVIOUS
| ActionType.NEXT
| ActionType.PLAY
| ActionType.PAUSE;
payload?: any;
}
| {
type: ActionType.GOTO;
payload: number;
};
License
MIT © gdo-bzh