Search code examples
reactjssliderreact-bootstrapbootstrap-carousel

React-Bootstrap carousel slider: how to detect current slide in display


I have a bootstrap slider (through the library: React-Bootstrap) and would like to find a way to detect the current slide in display (through classes code and not hooks). Here is the Slider component:

//import image1, image2, image3

class HeroSlider extends Component {

  handleSelect(){
    console.log('this sets the slide, but I just want to know the index of current slide')
  }

  render(){
  return (
    <Carousel indicators={false} controls={false} pause={false} onSelect={this.handleSelect()}>
      <Carousel.Item>
        <img className="d-block w-100" src={image1} alt="First slide" />
      </Carousel.Item>
      <Carousel.Item>
        <img className="d-block w-100" src={image2} alt="Third slide" />
      </Carousel.Item>
      <Carousel.Item>
        <img className="d-block w-100" src={image3} alt="Third slide" />
      </Carousel.Item>
    </Carousel>
  );
      }
}

export default HeroSlider

How could I go about this? Thank you.


Solution

  • Okay, here is how I solved it:

    The functions/properties provided with react-bootstrap carousel won't help in detecting a change in slide index, they will just allow you to set it.

    I wanted to have an image background slider that infinitely rotates while stopping at each image for 3 seconds. So I ended up just setting the state to update the index every 3 seconds using an interval function. Here is the code:

    class HeroSlider extends Component {
      constructor(props, context) {
        super(props, context);
    
        this.state = {
          index: 0,
        };
      }
      componentDidMount() {
        this.interval = setInterval(
          () => this.setState({ index: (this.state.index + 1) % 7 }), 
          3000
        );
      }
      componentWillUnmount() {
        clearInterval(this.interval);
      }
    
      render(){
      return (
        <Carousel indicators={false} controls={false} pause={false} onSelect={this.handleSelect()}>
          <Carousel.Item>
            <img className="d-block w-100" src={image1} alt="First slide" />
          </Carousel.Item>
          <Carousel.Item>
            <img className="d-block w-100" src={image2} alt="Third slide" />
          </Carousel.Item>
          <Carousel.Item>
            <img className="d-block w-100" src={image3} alt="Third slide" />
          </Carousel.Item>
        </Carousel>
      );
          }
    }
    
    export default HeroSlider
    
    

    Now if I want to detect current slider index I simply acces this.state.index.