DEV Community

Patrick Moore
Patrick Moore

Posted on

Building Carousels with react-slick in React

react-slick is a popular React carousel component built on top of Slick Carousel. It provides a feature-rich carousel solution with extensive customization options, responsive breakpoints, and smooth animations. This guide walks through setting up and creating carousels using react-slick with React, from installation to a working implementation. This is part on using react-slick with React.

Prerequisites

Before you begin, make sure you have:

  • Node.js version 14.0 or higher installed
  • npm, yarn, or pnpm package manager
  • A React project (version 16.8 or higher) or create-react-app setup
  • Basic knowledge of React hooks (useState, useRef)
  • Familiarity with JavaScript/TypeScript
  • Understanding of CSS

Installation

Install react-slick and slick-carousel CSS:

npm install react-slick slick-carousel
Enter fullscreen mode Exit fullscreen mode

Or with yarn:

yarn add react-slick slick-carousel
Enter fullscreen mode Exit fullscreen mode

Or with pnpm:

pnpm add react-slick slick-carousel
Enter fullscreen mode Exit fullscreen mode

After installation, your package.json should include:

{
  "dependencies": {
    "react-slick": "^0.29.0",
    "slick-carousel": "^1.8.1",
    "react": "^18.0.0",
    "react-dom": "^18.0.0"
  }
}
Enter fullscreen mode Exit fullscreen mode

Project Setup

Import the CSS files in your main entry file:

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
Enter fullscreen mode Exit fullscreen mode

First Example / Basic Usage

Let's create a simple image carousel. Create a new file src/SlickExample.jsx:

// src/SlickExample.jsx
import React from 'react';
import Slider from 'react-slick';

function SlickExample() {
  const images = [
    'https://via.placeholder.com/800x400/007bff/ffffff?text=Slide+1',
    'https://via.placeholder.com/800x400/28a745/ffffff?text=Slide+2',
    'https://via.placeholder.com/800x400/ffc107/000000?text=Slide+3',
    'https://via.placeholder.com/800x400/dc3545/ffffff?text=Slide+4'
  ];

  const settings = {
    dots: true,
    infinite: true,
    speed: 500,
    slidesToShow: 1,
    slidesToScroll: 1,
    autoplay: true,
    autoplaySpeed: 3000
  };

  return (
    <div style={{ padding: '20px', maxWidth: '800px', margin: '0 auto' }}>
      <h2>Basic Slick Carousel Example</h2>
      <Slider {...settings}>
        {images.map((image, index) => (
          <div key={index}>
            <img
              src={image}
              alt={`Slide ${index + 1}`}
              style={{ width: '100%', height: '400px', objectFit: 'cover' }}
            />
          </div>
        ))}
      </Slider>
    </div>
  );
}

export default SlickExample;
Enter fullscreen mode Exit fullscreen mode

Update your App.jsx:

// src/App.jsx
import React from 'react';
import SlickExample from './SlickExample';
import './App.css';

function App() {
  return (
    <div className="App">
      <SlickExample />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

This creates a basic carousel with navigation dots and autoplay.

Understanding the Basics

react-slick provides extensive configuration options:

  • Slider component: Main carousel component
  • Settings object: Configuration for carousel behavior
  • Responsive breakpoints: Different settings for different screen sizes
  • Custom arrows: Customizable navigation arrows
  • Multiple slides: Show multiple slides at once
  • Touch support: Swipe gestures on mobile

Key concepts:

  • Settings object: Configure carousel through a settings prop
  • Slides structure: Each slide is wrapped in a div
  • Responsive: Use responsive array for breakpoint-specific settings
  • Custom components: Customize arrows, dots, and other elements
  • Event handlers: Use callbacks for slide changes and interactions

Here's an example with responsive breakpoints:

// src/ResponsiveSlickExample.jsx
import React from 'react';
import Slider from 'react-slick';

function ResponsiveSlickExample() {
  const images = [
    'https://via.placeholder.com/800x400/007bff/ffffff?text=Slide+1',
    'https://via.placeholder.com/800x400/28a745/ffffff?text=Slide+2',
    'https://via.placeholder.com/800x400/ffc107/000000?text=Slide+3',
    'https://via.placeholder.com/800x400/dc3545/ffffff?text=Slide+4',
    'https://via.placeholder.com/800x400/6c757d/ffffff?text=Slide+5'
  ];

  const settings = {
    dots: true,
    infinite: true,
    speed: 500,
    slidesToShow: 1,
    slidesToScroll: 1,
    autoplay: true,
    autoplaySpeed: 3000,
    responsive: [
      {
        breakpoint: 1024,
        settings: {
          slidesToShow: 2,
          slidesToScroll: 2
        }
      },
      {
        breakpoint: 768,
        settings: {
          slidesToShow: 1,
          slidesToScroll: 1
        }
      }
    ]
  };

  return (
    <div style={{ padding: '20px', maxWidth: '1200px', margin: '0 auto' }}>
      <h2>Responsive Slick Carousel</h2>
      <Slider {...settings}>
        {images.map((image, index) => (
          <div key={index} style={{ padding: '0 10px' }}>
            <img
              src={image}
              alt={`Slide ${index + 1}`}
              style={{ width: '100%', height: '300px', objectFit: 'cover', borderRadius: '8px' }}
            />
          </div>
        ))}
      </Slider>
    </div>
  );
}

export default ResponsiveSlickExample;
Enter fullscreen mode Exit fullscreen mode

Practical Example / Building Something Real

Let's build a comprehensive image gallery with custom controls:

// src/ImageGallerySlick.jsx
import React, { useRef, useState } from 'react';
import Slider from 'react-slick';

function ImageGallerySlick() {
  const sliderRef = useRef(null);
  const [currentSlide, setCurrentSlide] = useState(0);

  const images = [
    {
      url: 'https://via.placeholder.com/800x500/007bff/ffffff?text=Image+1',
      title: 'Image 1',
      description: 'Description for image 1'
    },
    {
      url: 'https://via.placeholder.com/800x500/28a745/ffffff?text=Image+2',
      title: 'Image 2',
      description: 'Description for image 2'
    },
    {
      url: 'https://via.placeholder.com/800x500/ffc107/000000?text=Image+3',
      title: 'Image 3',
      description: 'Description for image 3'
    },
    {
      url: 'https://via.placeholder.com/800x500/dc3545/ffffff?text=Image+4',
      title: 'Image 4',
      description: 'Description for image 4'
    },
    {
      url: 'https://via.placeholder.com/800x500/6c757d/ffffff?text=Image+5',
      title: 'Image 5',
      description: 'Description for image 5'
    }
  ];

  const settings = {
    dots: true,
    infinite: true,
    speed: 500,
    slidesToShow: 1,
    slidesToScroll: 1,
    autoplay: false,
    arrows: true,
    beforeChange: (current, next) => setCurrentSlide(next)
  };

  const goToSlide = (index) => {
    sliderRef.current.slickGoTo(index);
  };

  return (
    <div style={{ padding: '20px', maxWidth: '900px', margin: '0 auto' }}>
      <h1>Image Gallery with Slick</h1>
      <div style={{ position: 'relative', marginBottom: '20px' }}>
        <Slider ref={sliderRef} {...settings}>
          {images.map((image, index) => (
            <div key={index}>
              <div style={{ position: 'relative' }}>
                <img
                  src={image.url}
                  alt={image.title}
                  style={{ width: '100%', height: '500px', objectFit: 'cover' }}
                />
                <div style={{
                  position: 'absolute',
                  bottom: 0,
                  left: 0,
                  right: 0,
                  background: 'linear-gradient(to top, rgba(0,0,0,0.7), transparent)',
                  color: 'white',
                  padding: '20px'
                }}>
                  <h3 style={{ margin: '0 0 5px 0' }}>{image.title}</h3>
                  <p style={{ margin: 0 }}>{image.description}</p>
                </div>
              </div>
            </div>
          ))}
        </Slider>
      </div>
      <div style={{ textAlign: 'center', marginBottom: '20px', color: '#666' }}>
        Image {currentSlide + 1} of {images.length}
      </div>
      <div style={{ display: 'flex', justifyContent: 'center', gap: '10px', flexWrap: 'wrap' }}>
        {images.map((image, index) => (
          <img
            key={index}
            src={image.url}
            alt={image.title}
            onClick={() => goToSlide(index)}
            style={{
              width: '100px',
              height: '100px',
              objectFit: 'cover',
              borderRadius: '4px',
              cursor: 'pointer',
              border: currentSlide === index ? '3px solid #007bff' : '1px solid #ddd',
              opacity: currentSlide === index ? 1 : 0.7
            }}
          />
        ))}
      </div>
    </div>
  );
}

export default ImageGallerySlick;
Enter fullscreen mode Exit fullscreen mode

Now create a product carousel:

// src/ProductCarouselSlick.jsx
import React from 'react';
import Slider from 'react-slick';

function ProductCarouselSlick() {
  const products = [
    { id: 1, name: 'Product 1', price: '$99', image: 'https://via.placeholder.com/300x300/007bff/ffffff?text=Product+1' },
    { id: 2, name: 'Product 2', price: '$149', image: 'https://via.placeholder.com/300x300/28a745/ffffff?text=Product+2' },
    { id: 3, name: 'Product 3', price: '$199', image: 'https://via.placeholder.com/300x300/ffc107/000000?text=Product+3' },
    { id: 4, name: 'Product 4', price: '$249', image: 'https://via.placeholder.com/300x300/dc3545/ffffff?text=Product+4' },
    { id: 5, name: 'Product 5', price: '$299', image: 'https://via.placeholder.com/300x300/6c757d/ffffff?text=Product+5' },
    { id: 6, name: 'Product 6', price: '$349', image: 'https://via.placeholder.com/300x300/17a2b8/ffffff?text=Product+6' }
  ];

  const settings = {
    dots: true,
    infinite: true,
    speed: 500,
    slidesToShow: 3,
    slidesToScroll: 1,
    autoplay: true,
    autoplaySpeed: 3000,
    responsive: [
      {
        breakpoint: 1024,
        settings: {
          slidesToShow: 2,
          slidesToScroll: 1
        }
      },
      {
        breakpoint: 768,
        settings: {
          slidesToShow: 1,
          slidesToScroll: 1
        }
      }
    ]
  };

  return (
    <div style={{ padding: '20px', maxWidth: '1200px', margin: '0 auto' }}>
      <h2>Product Carousel</h2>
      <Slider {...settings}>
        {products.map((product) => (
          <div key={product.id} style={{ padding: '0 10px' }}>
            <div style={{
              padding: '15px',
              textAlign: 'center',
              backgroundColor: '#f8f9fa',
              borderRadius: '8px',
              height: '100%'
            }}>
              <img
                src={product.image}
                alt={product.name}
                style={{
                  width: '100%',
                  height: '250px',
                  objectFit: 'cover',
                  borderRadius: '4px',
                  marginBottom: '10px'
                }}
              />
              <h3 style={{ margin: '0 0 5px 0' }}>{product.name}</h3>
              <p style={{ margin: 0, fontWeight: 'bold', color: '#007bff' }}>{product.price}</p>
            </div>
          </div>
        ))}
      </Slider>
    </div>
  );
}

export default ProductCarouselSlick;
Enter fullscreen mode Exit fullscreen mode

Update your App.jsx:

// src/App.jsx
import React from 'react';
import ImageGallerySlick from './ImageGallerySlick';
import ProductCarouselSlick from './ProductCarouselSlick';
import './App.css';

function App() {
  return (
    <div className="App">
      <ImageGallerySlick />
      <ProductCarouselSlick />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

This example demonstrates:

  • Image gallery with custom controls
  • Product carousel with multiple slides
  • Responsive breakpoints
  • Thumbnail navigation
  • Programmatic slide control
  • Custom styling

Common Issues / Troubleshooting

  1. Carousel not displaying: Make sure you've imported both CSS files (slick.css and slick-theme.css). The carousel requires these styles to render correctly.

  2. Arrows not showing: Check that arrows: true is set in settings. Also ensure the CSS files are imported correctly, as arrows are styled by the theme CSS.

  3. Responsive not working: Use the responsive array in settings. Each breakpoint object should have a breakpoint (in pixels) and settings object.

  4. Autoplay not working: Set autoplay: true and specify autoplaySpeed in milliseconds. Also ensure infinite: true for continuous playback.

  5. Slides not aligned: Use slidesToShow and slidesToScroll to control how many slides are visible and how many scroll at a time. Add padding to slides using inline styles or CSS.

  6. Ref not working: Use useRef to create a ref and pass it to the Slider component. Access methods like slickGoTo(), slickNext(), and slickPrev() through the ref.

Next Steps

Now that you have an understanding of react-slick:

  • Explore all available settings and options
  • Learn about custom arrows and dots
  • Implement lazy loading for images
  • Add custom animations
  • Create vertical carousels
  • Learn about other carousel libraries (swiper, react-responsive-carousel)
  • Check the official repository: https://github.com/akiran/react-slick

Summary

You've successfully integrated react-slick into your React application and created image galleries and product carousels with responsive breakpoints and custom controls. react-slick provides a powerful, feature-rich solution for creating carousels with extensive customization options.

SEO Keywords

react-slick
React carousel component
react-slick tutorial
React Slick Carousel
react-slick installation
React image carousel
react-slick example
React slider component
react-slick setup
React responsive carousel
react-slick customization
React carousel library
react-slick breakpoints
React slick settings
react-slick getting started

Top comments (0)