Ad

Loading Dynamic Images (fetched Using API) In 'react-responsive-carousel' React

I really like 'react-responsive-carousel' and it perfectly fits my requirements.

More Details: https://www.npmjs.com/package/react-responsive-carousel

However I realized that the demo examples provided by this uses static images, placed in separate "Carousel.js" file.

In my case, I want to load images in Carousel, that I'm fetching using API at runtime. I don't have any clue about how can I achieve this behavior.

Currently following is the setup of my app: File: Carousel.js

import React from "react";
import { Carousel } from "react-responsive-carousel";

export default () => (
  <Carousel autoPlay infiniteLoop='true'>
    <div>
      <img src="http://example.com/image/32.png" />
      <p className="legend">Image 1</p>
    </div>
    <div>
      <img src="http://example.com/image/34.png" />
      <p className="legend">Image 2</p>
    </div>
    <div>
      <img src="http://example.com/mockups/image/9.png" />
      <p className="legend">Image 3</p>
    </div>
    <div>
      <img src="http://example.com/image/32.png" />
      <p className="legend">Image 4</p>
    </div>
    <div>
      <img src="http://example.com/image/34.png" />
      <p className="legend">Image 5</p>
    </div>
  </Carousel>
);

In my App.js file, I am simply using it in the following way:

<div>
<div className="my-carousel">
<Carousel />
</div>
</div>
Ad

Answer

Here's a basic flow, that you can tune-up for your needs:

  1. First of all you have to fetch the images.
  2. After that you have to keep the images in the component's state.
  3. Finally, render the <Carousel /> with the state's images.

Here's a pseudo code:

import React from 'react'
import { Carousel } from 'react-responsive-carousel'

class App extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      images: null
    }
  }

  componentDidMount() {
    // #1. First of all you have to fetch the images.
    fetch('https://example.com/images-api-endpoint')
      .then(response => response.json()) // If it's a JSON response, you have to parse it firstly
      .then(images => this.setState({ images })) // #2. After that you have to keep the images in the component's state.
  }

  render () {
    const { images } = this.state

    if (!images) return <div>Images are not fetched yet!</div>

    // #3. Finally, render the `<Carousel />` with the state's images.
    return <Carousel autoPlay infiniteLoop='true'>
      {
        images.map( image => {
          return <div>
            <img src={ image.path } />
            <p className="legend">{ image.name }</p>
          </div>
        })
      }
    </Carousel>
  }
}

Keep in mind in the above flow aren't included some concepts, because they are out of the question's scope. For example:

  1. Showing a Loading indicator, while fetching the images.
  2. Error handling, if the API request fails.
Ad
source: stackoverflow.com
Ad