Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to create a react slider component

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
    }    
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading