B
B
brainexplosion2018-08-17 11:16:13
React
brainexplosion, 2018-08-17 11:16:13

How to create a carusel with React?

I am using React-Bootstrap to create a Carusel. Here is the code:

import React, { Component } from 'react';
import "./index.css";
import { Carousel} from 'react-bootstrap';



class ControlledCarousel extends React.Component {
  constructor(props, context) {
    super(props, context);
  
    this.handleSelect = this.handleSelect.bind(this);
  
    this.state = {
    index: 0,
    direction: null, 
    };
  }
  
  handleSelect(selectedIndex, e) {
   
    this.setState({
    index: selectedIndex,
    direction: e.direction
    });
  }
  
  render() {
    const { index, direction } = this.state;
  
    return (
       <Carousel
        activeIndex={index}
        direction={direction}
        onSelect={this.handleSelect}
       >
        <Carousel.Item>
          <img width={900} height={500} alt="900x500" src={this.state.img} />
          <Carousel.Caption>
            <h3>First slide label</h3>
            <p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p>
          </Carousel.Caption>
        </Carousel.Item>
        <Carousel.Item>
          <img width={900} height={500} alt="900x500" src={this.state.img} />
          <Carousel.Caption>
            <h3>Second slide label</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
          </Carousel.Caption>
        </Carousel.Item>
        <Carousel.Item>
          <img width={900} height={500} alt="900x500" src={this.state.img} />
          <Carousel.Caption>
            <h3>Third slide label</h3>
            <p>
              Praesent commodo cursus magna, vel scelerisque nisl consectetur.
            </p>
          </Carousel.Caption>
        </Carousel.Item>
      </Carousel>
    );
  }
  }
  

export default ControlledCarousel;

The question is this: how to create an array of images and output them by key, and not prescribe each image in src?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-08-17
@brainexplosion

Lists and keys

<Carousel
  activeIndex={index}
  direction={direction}
  onSelect={this.handleSelect}
>
  {items.map((item, index) => (
    <Carousel.Item key={index}>
      <img width={900} height={500} alt="900x500" src={item.src} />
      <Carousel.Caption>
        <h3>{item.label}</h3>
        <p>{item.caption}</p>
      </Carousel.Caption>
    </Carousel.Item>
  ))}
</Carousel>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question