Home > Net >  how to create a react slider component
how to create a react slider component

Time:08-05

I was trying to make a react slider component but for some reasons it doesn't change/update the image on click instead it always displays the same picture. What i'm trying to achieve is when I click the button it updates index and the display image changes according to index position. Even though the index is updating the image is not changing. My attempt at creating the slider component -

import arrow from '../../img/arrow-outlined-crimson.png';

const Slider = ({ images }) => {
  let index = 0;

  const nextSlide = () => {
    index =1;
    if (index > images.length - 1) {
      index = 0
    }
  }

  return (
    <div className='slider'>
      <div ref={sliderRef} className="wrapper">
        <img src={images[index]} alt="" className="sliderImg" />
      </div>
      <img src={arrow} onClick={nextSlide} alt="Arrow" className="sliderIcon iconRight" />
    </div>
  )
}

export default Slider

CodePudding user response:

Use React State instead of just variables.

Try this:

 const [index, setIndex] = React.useState(0)

  const nextSlide = () => {
    setIndex(index   1);
    if (index > images.length - 1) {
      setIndex(1)
    }    
  }
  • Related