Skip to content
Advertisement

React – carousel

I’m creating my own carousel and I want to add circles navigation on the bottom of slider. I am fetching data from mongoDb (3 pictures) and load them in App component and passing via props to Carousel component.

I want to map trough array and set index to data-slider property and later read this with e.target.dataset.slider and change in method changeSlider() to this value in data-slider property.

I have weird problem, when I click on this buttons circles sometimes I have value === 2, 0, 1 but sometimes I’m getting undefined and my slider don’t know which slider make active.

<div className="circle-container">
          {this.props.images.map((el, index) => {
            return (
              <button
                key={index}
                onClick={this.setActiveSlide}
                className="circle-empty"
                data-slider={index}
              >
                <i className="far fa-circle" />
              </button>
            );
          })}
        </div>

Method:

setActiveSlide = e => {
    let slider = e.target.dataset.slider;
    this.setState({
      slider: slider
    });
  };

Call setActiveSlide method onClick gave me this result:

enter image description here

Advertisement

Answer

Your event is probably firing from the icon sometimes simply change the event target to currentTarget

setActiveSlide = e => {
  // I've changed this variable to const because our data-slider is not
  // going to change.
  const slider = e.currentTarget.dataset.slider;
  // Using es6 object property shorthand if we have both
  // the same variable name and field we can simply pass in just the
  // field name and it will auto convert it for us
  this.setState({
    slider
  });
};
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement