react-slick

repository·master·Indexed 11 days ago

https://github.com/akiran/react-slick

A React port of the slick carousel providing a highly customizable carousel component. Version 0.31.0. Includes the Slider component with support for responsive breakpoints, custom navigation arrows via prevArrow and nextArrow, and custom pagination dots via customPaging and appendDots. Provides programmatic control methods such as slickPrev, slickNext, slickGoTo, slickPause, and slickPlay.

Tokens
2.9K
Snippets
12
Records
13
Agent score
95%

What's inside react-slick

  1. Customize next/prev arrows with React components

    master

    You can replace the default navigation arrows by passing custom React components to the nextArrow and prevArrow props.

    Critical Requirement: Your custom component must spread the incoming props (e.g., {...this.props}) onto the clickable element. If you fail to pass these props, the click handlers provided by react-slick will not trigger, and the arrows will not function.

    class LeftNavButton extends React.Component {
      render() {
        // You must spread this.props to ensure click handlers work
        return <button {...this.props}>Next</button>;
      }
    }
  2. Configure slick-carousel CSS

    master

    To ensure the carousel styles are applied, you must import the CSS files from slick-carousel. You can do this via npm imports in your JavaScript/TypeScript files or by adding CDN links to your HTML.

    // Import via npm
    import "slick-carousel/slick/slick.css";
    import "slick-carousel/slick/slick-theme.css";
    <!-- Or via CDN in your HTML -->
    <link
      rel="stylesheet"
      type="text/css"
      charset="UTF-8"
      href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css"
    />
    <link
      rel="stylesheet"
      type="text/css"
      href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.min.css"
    />
  3. Install react-slick

    master

    Install the react-slick package using npm or yarn.

    Note: You must also install slick-carousel to provide the necessary CSS and fonts for the carousel to render correctly.

    # Using npm
    npm install react-slick --save
    npm install slick-carousel
    
    # Using yarn
    yarn add react-slick
    yarn add slick-carousel
  4. Configure the `responsive` property for breakpoints

    master

    The responsive property allows you to change carousel settings based on the viewport width. It accepts an array of objects with the shape { breakpoint: number, settings: object | 'unslick' }.

    • The breakpoint value represents the maxWidth. Settings are applied when the resolution is below this value.
    • Breakpoints in the array must be ordered from smallest to greatest.
    • To disable the carousel entirely at a specific breakpoint, use the string 'unslick' instead of a settings object.
    [ 
      { breakpoint: 768, settings: { slidesToShow: 3 } }, 
      { breakpoint: 1024, settings: { slidesToShow: 5 } }, 
      { breakpoint: 100000, settings: 'unslick' } 
    ]
  5. Fix 'matchMedia not present' error in Jest tests

    master

    When running tests with Jest, you may encounter the error: matchMedia not present, legacy browsers require a polyfill.

    To resolve this, follow these two steps:

    1. Create a test-setup.js file and add a matchMedia polyfill.
    2. Configure Jest to use this setup file in your package.json.
    // test-setup.js
    window.matchMedia = 
      window.matchMedia || 
      function() {
        return {
          matches: false,
          addListener: function() {},
          removeListener: function() {}
        };
      };
    // package.json
    {
      "jest": {
        "setupFiles": ["test-setup.js"]
      }
    }
  6. Use the Slider component

    master

    Import the Slider component from react-slick and pass a settings object containing configuration props. The Slider component wraps the elements you want to include in the carousel.

    import React from "react";
    import Slider from "react-slick";
    
    export default function SimpleSlider() {
      var settings = {
        dots: true,
        infinite: true,
        speed: 500,
        slidesToShow: 1,
        slidesToScroll: 1
      };
      return (
        <Slider {...settings}>
          <div><h3>1</h3></div>
          <div><h3>2</h3></div>
          <div><h3>3</h3></div>
          <div><h3>4</h3></div>
          <div><h3>5</h3></div>
          <div><h3>6</h3></div>
        </Slider>
      );
    }
  7. Use Slick methods to control the slider

    master

    You can programmatically control the slider instance using the following methods. These are typically accessed via a ref attached to the Slider component.

    NameArgumentsDescription
    slickPrevNoneGo to the previous slide
    slickNextNoneGo to the next slide
    slickGoToindex, dontAnimateGo to the given slide index (where index is the target slide and dontAnimate is a boolean)
    slickPauseNonePause the autoplay
    slickPlayNoneStart the autoplay
    // Example usage pattern (conceptual):
    // const sliderRef = useRef(null);
    // <Slider ref={sliderRef}>...</Slider>
    // sliderRef.current.slickNext();
  8. Configure Playwright Component Testing for react-slick

    master

    The playwright-ct.config.js file defines the configuration for Playwright Component Testing (CT) using the @playwright/experimental-ct-react package. This configuration controls test directories, snapshot locations, timeouts, parallelization, and browser projects.

    Key configuration options include:

    • testDir: The directory where tests are located (set to ./playwright-tests).
    • snapshotDir: The base directory for snapshots created with toMatchSnapshot and toHaveScreenshot (set to ./__snapshots__).
    • timeout: Maximum execution time for a single test (set to 10 seconds).
    • fullyParallel: Enables running tests in files in parallel.
    • forbidOnly: Prevents accidental use of test.only in CI environments.
    • retries: Number of times to retry failed tests (2 on CI, 0 otherwise).
    • workers: Number of parallel workers (1 on CI to opt out of parallel tests, undefined otherwise).
    • reporter: The test reporter to use (set to html).

    Under the use object, you can configure:

    • trace: Controls trace collection (set to on-first-retry).
    • ctPort: The port used for the Playwright component endpoint (set to 3100).
    const { defineConfig, devices } = require("@playwright/experimental-ct-react");
    
    module.exports = defineConfig({
      testDir: "./playwright-tests",
      snapshotDir: "./__snapshots__",
      timeout: 10 * 1000,
      fullyParallel: true,
      forbidOnly: !!process.env.CI,
      retries: process.env.CI ? 2 : 0,
      workers: process.env.CI ? 1 : undefined,
      reporter: "html",
      use: {
        trace: "on-first-retry",
        ctPort: 3100
      },
      projects: [
        {
          name: "chromium",
          use: { ...devices["Desktop Chrome"] }
        }
      ]
    });
  9. Customize pagination dots with customPaging and appendDots

    master

    The Dots component (used internally for pagination) allows for customization of the dots' appearance and container via two primary props: customPaging and appendDots.

    • customPaging: A function that receives the dot index i and returns a React element. This element will be cloned and injected with an onClick handler.
    • appendDots: A function that receives the array of generated <li> dot elements and returns a React element (the container) that wraps them. This container can be styled using the dotsClass prop.

    Note: The onClick handler passed to customPaging elements is wrapped to prevent default behavior, ensuring compatibility with autoplay transitions.

    // Example conceptual usage of the customization pattern:
    // While Dots is an internal component, you provide these via the Slick settings
    const settings = {
      customPaging: (i) => <span className="my-custom-dot">{i + 1}</span>,
      appendDots: (dots) => <ul className="my-dots-container">{dots}</ul>,
      dotsClass: "my-dots-class"
    };
  10. Customize navigation arrows with prevArrow and nextArrow props

    master

    You can override the default navigation arrows by providing custom React elements to the prevArrow and nextArrow props of the Slider component.

    When you provide a custom component, react-slick will clone it and inject the following props into your component:

    • className: A string containing the necessary slick classes (e.g., slick-arrow slick-prev or slick-arrow slick-next). If the arrow is disabled, it will also include the slick-disabled class.
    • onClick: A function to trigger the navigation. For the previous arrow, it calls the handler with { message: 'previous' }; for the next arrow, it calls it with { message: 'next' }.
    • currentSlide: The index of the currently active slide.
    • slideCount: The total number of slides in the slider.
    • style: An object containing { display: 'block' }.
    • data-role: Set to 'none'.
    // Example of providing a custom arrow component
    <Slider
      nextArrow={<MyCustomNextArrow />}
      prevArrow={<MyCustomPrevArrow />}
    >
      <div>1</div>
      <div>2</div>
    </Slider>