Mizlul
Mizlul

Reputation: 2290

how to show image slider in React

I am using this plugin https://github.com/akiran/react-slick for image slider but for some reason i am unable to achieve what I want.

Here is a sample code:

import React, { Component } from "react";
import Slider from "../src/slider";
import { baseUrl } from "./config";

export default class CenterMode extends Component {
  render() {
    const settings = {
      customPaging: function(i) {
        return (
          <a>
            <img src={`${baseUrl}/abstract0${i + 1}.jpg`} />
          </a>
        );
      },
      dots: true,
      dotsClass: "slick-dots slick-thumb",
      infinite: true,
      speed: 500,
      slidesToShow: 1,
      slidesToScroll: 1
    };
    return (
      <div>
        <h2>Custom Paging</h2>
        <Slider {...settings}>
          <div>
            <img src={baseUrl + "/abstract01.jpg"} />
          </div>
          <div>
            <img src={baseUrl + "/abstract02.jpg"} />
          </div>
          <div>
            <img src={baseUrl + "/abstract03.jpg"} />
          </div>
          <div>
            <img src={baseUrl + "/abstract04.jpg"} />
          </div>
        </Slider>
      </div>
    );
  }
}

This works perfectly fine unless the image file names are like abstract01, abstract02, in my case image file name is random it can be anything, thus the thumbnail part does not work for me. Are there any option that I can pass some other argument on the customPaging so that i can receive src attr and can get the file name from there.

Any idea would be much appreciated here. Note: the images in my case are coming from amazon s3, so I have no control over them at all!

Upvotes: 2

Views: 5331

Answers (1)

Droow
Droow

Reputation: 416

I believe you can do something like this:

const images = [
  { src: baseUrl + "/abstract01.jpg" },
  { src: baseUrl + "/abstract02.jpg" },
  { src: baseUrl + "/abstract03.jpg" },
  { src: baseUrl + "/abstract04.jpg" },
];

export default class App extends Component {
  render() {
    const settings = {
      customPaging: function (i) {
        return (
          <a>
            <img src={images[i].src} />
          </a>
        );
      },
      dots: true,
      dotsClass: "slick-dots slick-thumb",
      infinite: true,
      speed: 500,
      slidesToShow: 1,
      slidesToScroll: 1
    };
    return (
      <div>
        <h2>Custom Paging</h2>
        <Slider {...settings}>
          {images.map((img) => (
            <div>
              <img src={img.src} />
            </div>
          ))}
        </Slider>
      </div>
    );
  }
}

Basically you can create the image array (because you already know the images) and then map through it to get the slides and use the iterator in custom paging to get the image by index from your array.

Upvotes: 3

Related Questions