Z
Z
Zbiten2018-02-24 11:12:48
JavaScript
Zbiten, 2018-02-24 11:12:48

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'
];

On click on the next button, I want to increase the current index by +1, thus changing the current image.
How to do it? Or is it worth using state for this?
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

1 answer(s)
R
Roman Aleksandrovich, 2018-02-24
@Zbiten

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;

In this code, there is not enough check when clicking on next, a situation is possible when the number of photos is 3 and the user clicked 4, an error will occur. The same goes for the prev button.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question