user3209048 user3209048 - 1 month ago 21
React JSX Question

reactjs image slider navigation function, cant seem to get it working properly

i have a simple image slider with 3 images contained in an array and i just wish to navigate the slider with just 1 function that can go back and forth between images and if you click next on the last image it brings you to first image and vice versa, this is what i could make but its not working properly, instead it displays nothing if you click back on first image, and display nothing as well when you click next after last image

constructor() {
super()
this.state = {
imgArray: [ "/img/work1.jpg", "/img/work2.jpg", "/img/work3.jpg"],
imgNo: 0,
imgArrayLength: 2,
current: "/img/work1.jpg",
headlines: ["Pink Floyd Office", "Led Zeppelin Mania", "Central Perk Friends"],
headline : "Pink Floyd Office"
};
}

changeImg(n){
this.setState({
imgNo: this.state.imgNo += n
})
if(this.state.imgNo > this.state.imgArrayLength){
this.setState({
imgNo: 0
})
}
else if(this.state.imgNo < 0){
this.setState({
imgNo: this.state.imgArrayLength
})
}
this.setState({
current: this.state.imgArray[this.state.imgNo],
headline: this.state.headlines[this.state.imgNo]
})
}

<img src="/img/slider-left.png" class="slider-arrow" onClick={this.changeImg.bind(this, -1)} />
<img src="/img/slider-right.png" class="slider-arrow slider-right" onClick={this.changeImg.bind(this, 1)} />

Answer

You can calculate imgNo using - (imgArrayLength + imgNo + n) % imgArrayLength:

changeImg(n) {
  const {
    imgArrayLength, imgNo
  } = this.state;

  const current = (imgArrayLength + imgNo + n) % imgArrayLength;

  this.setState({
    imgNo: current,
    current: this.state.imgArray[current],
    headline: this.state.headlines[current]
  })
}

I would also remove this props from the state because they are redundant:

current: this.state.imgArray[current],
headline: this.state.headlines[current]

In the render method use this.state.imgArray[this.state.imgNo].

Comments