Answer the question
In order to leave comments, you need to log in
How to implement image switching (slider) on click?
I have an array of images:
[
'https://picsum.photos/500/300?image=0',
'https://picsum.photos/500/300?image=44',
'https://picsum.photos/500/300?image=22'
];
import React, { Component } from 'react';
class Slider extends Component {
render() {
let currentSlideImage = 0;
return (
<div className="container">
<button onClick={this.handlePrevButton}>Prev</button>
<img src={this.props.slides[currentSlideImage]} alt="slider-item"/>
<button onClick={this.handleNextButton}>Next</button>
</div>
);
}
handlePrevButton = () => {
console.log('prev')
}
handleNextButton = () => {
currentSlideImage++;
}
}
export default Slider;
Answer the question
In order to leave comments, you need to log in
did you set out to write a slider yourself or just didn’t find a normal ready-made one?
The answer to your question is no matter where you store the currentSlideImage in the state or in the store (if you use redux). But if you use the state, switching will be faster and I think it’s more correct at this moment, unless of course it’s important for you to show the last slide on which the user stopped when you re-enter the page with this slider.
import React, { Component } from 'react';
class Slider extends Component {
constructor(props){
super()
this.state=({
currentSlideImage : 0
})
}
handlePrevButton(){
let currentSlideImage = this.state.currentSlideImage;
this.setState({
currentSlideImage:currentSlideImage-1
})
}
handleNextButton(){
let currentSlideImage = this.state.currentSlideImage;
this.setState({
currentSlideImage:currentSlideImage+1
})
}
render() {
return (
<div className="container">
<button onClick={()=>this.handlePrevButton()}>Prev</button>
<img src={this.props.slides[this.state.currentSlideImage]} alt="slider-item"/>
<button onClick={()=>this.handleNextButton()}>Next</button>
</div>
);
}
}
export default Slider;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question