Weekly Webtips
Published in

Weekly Webtips

Image Slider using React Slick

Image Slider with React Slick

Installation

yarn add react-slick
yarn add @types/react-slick

Usage

// Style.css
@import url('https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.min.css');
@import url('https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick-theme.min.css');

Click Events of Slider Arrow

const sliderRef = useRef<Slider>(null);
..........
return (
<SliderWrapper>
<SliderArrow type="prev" onClick={() => sliderRef.current.slickPrev()} />}
.................
<SliderArrow type="next" onClick={() => sliderRef.current.slickNext()} />}
</SliderWrapper>
);

Advanced Features

const settings: Settings = {
.......,
afterChange: (currentSlide: number) => handleChangeSlide(currentSlide)
}
const [showRightArrow, setShowRightArrow] = useState<boolean>(false);
const [showLeftArrow, setShowLeftArrow] = useState<boolean>(false);
const [maxNumberOfCardsToShow, setMaxNumberOfCardsToShow] = useState<number>(0);
const handleChangeSlide = (currentSlide: number) => {
const leftArrowVisible = currentSlide !== 0;
const rightArrowVisible = currentSlide <= data.length - maxNumberOfCardsToShow;
setShowLeftArrow(leftArrowVisible);
setShowRightArrow(rightArrowVisible);
};
{showLeftArrow && ( <SliderArrow type="prev" onClick={() => sliderRef.current.slickPrev()} />)}
........
{showRightArrow && ( <SliderArrow type="next" onClick={() => sliderRef.current.slickNext()} />)}
const sliderWrapperRef = useRef<HTMLDivElement>(null);...<SliderWrapper ref={sliderWrapperRef}>
useEffect(() => {
const wrapperWidth = sliderWrapperRef.current.clientWidth || 0;

const maxNumberOfCards = Math.ceil(wrapperWidth / EACH_SLIDE_WIDTH);

setMaxNumberOfCardsToShow(maxNumberOfCards);
setShowRightArrow(data.length > maxNumberOfCards);
}, []);
const EACH_SLIDE_WIDTH = 176;

--

--

Explore the world of web technologies through a series of tutorials

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ashraful Islam

Software Engineer | Javascript Developer | React | React Native | Angular | NodeJS