DEV Community

Joseph Nelson
Joseph Nelson

Posted on

Advanced Image Sliders with react-awesome-slider in React

react-awesome-slider is a full-featured, performant slider component for React applications. It provides smooth animations, touch gestures, keyboard navigation, and extensive customization options for creating professional image galleries and content sliders. This guide walks through advanced usage of react-awesome-slider with React, including custom animations, autoplay, and complex slider configurations. This is part 57 of a series on using react-awesome-slider with React.

Demo animation

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, useEffect, useRef)
  • Familiarity with CSS animations
  • Understanding of touch events and gestures

Installation

Install react-awesome-slider and required CSS:

npm install react-awesome-slider core-js
Enter fullscreen mode Exit fullscreen mode

Or with yarn:

yarn add react-awesome-slider core-js
Enter fullscreen mode Exit fullscreen mode

Or with pnpm:

pnpm add react-awesome-slider core-js
Enter fullscreen mode Exit fullscreen mode

After installation, your package.json should include:

{
  "dependencies": {
    "react-awesome-slider": "^4.1.0",
    "core-js": "^3.0.0",
    "react": "^18.0.0",
    "react-dom": "^18.0.0"
  }
}
Enter fullscreen mode Exit fullscreen mode

Project Setup

Import the CSS file in your main entry file:

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import 'react-awesome-slider/dist/styles.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 slider. Create a new file src/SliderExample.jsx:

// src/SliderExample.jsx
import React from 'react';
import AwesomeSlider from 'react-awesome-slider';
import 'react-awesome-slider/dist/styles.css';

function SliderExample() {
  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'
  ];

  return (
    <div style={{ padding: '20px', maxWidth: '800px', margin: '0 auto' }}>
      <h2>Basic Slider Example</h2>
      <AwesomeSlider>
        {images.map((image, index) => (
          <div key={index} data-src={image} />
        ))}
      </AwesomeSlider>
    </div>
  );
}

export default SliderExample;
Enter fullscreen mode Exit fullscreen mode

Update your App.jsx:

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

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

export default App;
Enter fullscreen mode Exit fullscreen mode

This creates a basic image slider with navigation and touch support.

Understanding the Basics

react-awesome-slider provides several key features:

  • AwesomeSlider component: Main slider component
  • Animation styles: Multiple animation presets (foldOutAnimation, scaleOutAnimation, etc.)
  • Autoplay: Automatic slide progression
  • Touch gestures: Swipe support for mobile
  • Keyboard navigation: Arrow key support
  • Custom bullets: Customizable navigation dots
  • Media support: Images, videos, and custom content

Key concepts for advanced usage:

  • Animation: Choose from preset animations or create custom ones
  • Media sources: Use data-src attribute for images
  • Custom content: Add any React components as slides
  • Event handlers: Use onTransitionStart, onTransitionEnd callbacks
  • Controlled mode: Control slider programmatically with refs

Here's an example with custom animations and autoplay:

// src/AdvancedSliderExample.jsx
import React from 'react';
import AwesomeSlider from 'react-awesome-slider';
import withAutoplay from 'react-awesome-slider/dist/autoplay';
import 'react-awesome-slider/dist/styles.css';

const AutoplaySlider = withAutoplay(AwesomeSlider);

function AdvancedSliderExample() {
  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'
  ];

  return (
    <div style={{ padding: '20px', maxWidth: '800px', margin: '0 auto' }}>
      <h2>Advanced Slider with Autoplay</h2>
      <AutoplaySlider
        play={true}
        cancelOnInteraction={false}
        interval={3000}
        animation="foldOutAnimation"
      >
        {images.map((image, index) => (
          <div key={index} data-src={image} />
        ))}
      </AutoplaySlider>
    </div>
  );
}

export default AdvancedSliderExample;
Enter fullscreen mode Exit fullscreen mode

Practical Example / Building Something Real

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

// src/ImageGallerySlider.jsx
import React, { useState, useRef } from 'react';
import AwesomeSlider from 'react-awesome-slider';
import withAutoplay from 'react-awesome-slider/dist/autoplay';
import 'react-awesome-slider/dist/styles.css';

const AutoplaySlider = withAutoplay(AwesomeSlider);

function ImageGallerySlider() {
  const sliderRef = useRef(null);
  const [currentSlide, setCurrentSlide] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);

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

  const handleNext = () => {
    sliderRef.current?.next();
  };

  const handlePrev = () => {
    sliderRef.current?.prev();
  };

  const handleGoToSlide = (index) => {
    sliderRef.current?.goto(index);
  };

  const handleTransitionStart = (entry) => {
    setCurrentSlide(entry.index);
  };

  return (
    <div style={{ padding: '20px', maxWidth: '900px', margin: '0 auto' }}>
      <h1>Image Gallery Slider</h1>

      <div style={{ position: 'relative', marginBottom: '20px' }}>
        <AutoplaySlider
          ref={sliderRef}
          play={isPlaying}
          cancelOnInteraction={true}
          interval={4000}
          animation="foldOutAnimation"
          onTransitionStart={handleTransitionStart}
          bullets={false}
          organicArrows={true}
        >
          {images.map((image, index) => (
            <div key={index} data-src={image.src}>
              <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>
          ))}
        </AutoplaySlider>
      </div>

      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: '10px', marginBottom: '20px' }}>
        <button
          onClick={handlePrev}
          style={{
            padding: '10px 20px',
            backgroundColor: '#007bff',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer'
          }}
        >
          Previous
        </button>
        <button
          onClick={() => setIsPlaying(!isPlaying)}
          style={{
            padding: '10px 20px',
            backgroundColor: isPlaying ? '#dc3545' : '#28a745',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer'
          }}
        >
          {isPlaying ? 'Pause' : 'Play'}
        </button>
        <button
          onClick={handleNext}
          style={{
            padding: '10px 20px',
            backgroundColor: '#007bff',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer'
          }}
        >
          Next
        </button>
      </div>

      <div style={{ display: 'flex', justifyContent: 'center', gap: '10px' }}>
        {images.map((_, index) => (
          <button
            key={index}
            onClick={() => handleGoToSlide(index)}
            style={{
              width: '12px',
              height: '12px',
              borderRadius: '50%',
              border: 'none',
              backgroundColor: currentSlide === index ? '#007bff' : '#ccc',
              cursor: 'pointer',
              transition: 'background-color 0.3s'
            }}
            aria-label={`Go to slide ${index + 1}`}
          />
        ))}
      </div>

      <div style={{ marginTop: '20px', textAlign: 'center', color: '#666' }}>
        Slide {currentSlide + 1} of {images.length}
      </div>
    </div>
  );
}

export default ImageGallerySlider;
Enter fullscreen mode Exit fullscreen mode

Now create a video slider:

// src/VideoSlider.jsx
import React from 'react';
import AwesomeSlider from 'react-awesome-slider';
import 'react-awesome-slider/dist/styles.css';

function VideoSlider() {
  const media = [
    {
      type: 'image',
      src: 'https://via.placeholder.com/800x450/007bff/ffffff?text=Image+1'
    },
    {
      type: 'video',
      src: 'https://www.w3schools.com/html/mov_bbb.mp4'
    },
    {
      type: 'image',
      src: 'https://via.placeholder.com/800x450/28a745/ffffff?text=Image+2'
    }
  ];

  return (
    <div style={{ padding: '20px', maxWidth: '800px', margin: '0 auto' }}>
      <h2>Mixed Media Slider</h2>
      <AwesomeSlider animation="scaleOutAnimation">
        {media.map((item, index) => (
          <div key={index} data-src={item.src}>
            {item.type === 'video' && (
              <video
                src={item.src}
                autoPlay
                loop
                muted
                style={{ width: '100%', height: '100%', objectFit: 'cover' }}
              />
            )}
          </div>
        ))}
      </AwesomeSlider>
    </div>
  );
}

export default VideoSlider;
Enter fullscreen mode Exit fullscreen mode

Update your App.jsx:

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

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

export default App;
Enter fullscreen mode Exit fullscreen mode

This example demonstrates:

  • Image gallery with custom controls
  • Autoplay functionality
  • Programmatic navigation
  • Custom bullets
  • Slide transitions
  • Mixed media support
  • Event handling

Common Issues / Troubleshooting

  1. Slider not displaying: Make sure you've imported the CSS file (import 'react-awesome-slider/dist/styles.css'). The slider requires styles to render correctly.

  2. Images not loading: Use the data-src attribute for images. Ensure image URLs are accessible and valid.

  3. Autoplay not working: Import and use the withAutoplay HOC. Make sure play prop is set to true and interval is specified.

  4. Navigation not working: Check that you're using the ref correctly. The slider methods (next(), prev(), goto()) are available on the ref.

  5. Animations not smooth: Ensure you're using valid animation names. Common animations include foldOutAnimation, scaleOutAnimation, cubeAnimation.

  6. Touch gestures not working: The slider includes touch support by default. If gestures aren't working, check for CSS conflicts or z-index issues.

Next Steps

Now that you have an advanced understanding of react-awesome-slider:

  • Explore all available animation styles
  • Learn about custom animations and transitions
  • Implement lazy loading for images
  • Add thumbnail navigation
  • Create fullscreen gallery mode
  • Integrate with image optimization libraries
  • Learn about other slider libraries (swiper, react-slick)
  • Check the official repository: https://github.com/rcaferati/react-awesome-slider
  • Look for part 58 of this series for more advanced topics

Summary

You've successfully integrated react-awesome-slider into your React application with advanced features including autoplay, custom controls, programmatic navigation, and mixed media support. react-awesome-slider provides a powerful, performant solution for creating professional image galleries and content sliders.

SEO Keywords

react-awesome-slider
React image slider
react-awesome-slider tutorial
React carousel component
react-awesome-slider installation
React slider gallery
react-awesome-slider example
React image gallery
react-awesome-slider setup
React autoplay slider
react-awesome-slider customization
React slider animations
react-awesome-slider controls
React slider library
react-awesome-slider getting started

Top comments (0)