How do I get autoplay to stop for videos on a Carousel made with React?

Viewed 417

I am very new to React and JavaScript altogether.
I am making a media carousel that displays both images and videos.
I have an auto-scroll feature where the slides change every 5 seconds. Thing is, I need that to NOT work on videos. I need the carousel to play the video completely and then move on to the next slide when it's done.
I have been racking my brain but I just cant figure out how to do that.
I'd really appreciate it if someone Helped me out.
Here's the code:

import { SliderData } from './SliderData'
import {FaArrowAltCircleRight, FaArrowAltCircleLeft } from 'react-icons/fa'

const ImageSlider = ({slides}) => {
  //Initiating Variables for index values and length of carousel 
  const [current, setCurrent] = useState(0);
  const length = slides.length

  const autoPlayRef = useRef()
  
  //Defining expression to loop carousel
  const nxt = () => {
    setCurrent(current === length-1 ? 0 : current+1)
  }
  const prv = () => {
    setCurrent(current === 0 ? length-1 : current-1)
  }

  //Defining a React hook for autoplay feature
  useEffect(() => {
    autoPlayRef.current = nxt;
  })
  useEffect(() => {
    const runn = () => {
      autoPlayRef.current()
    }
    const interval = setInterval(runn, 5000)
  }, [])

  //setting up a break case for when no items exist
  if (!Array.isArray(slides) || slides.length <=0) {
    return null;
  }

  return (
    <section className="slider">
      <FaArrowAltCircleLeft className="left-arrow" onClick={prv}/>
      <FaArrowAltCircleRight className="right-arrow" onClick={nxt}/>
      {SliderData.map((slide, index) => {
        return (
          <div className={index === current ? 'slide active' : 'slide'} key={index}>
            {index === current && ( SliderData[current].type === 2 ? (
              <video autoPlay muted className="vid">
                <source src={slide.image} type="video/mp4" />
              </video>
            ) : <img src={slide.image} alt="wallpaper" className="image"/>
            )}
          </div>
        );
      })}
    </section>
  );
};

// ImageSlider.defualtProps = {
//   slids: [],
//   autoPlay: null
// }

export default ImageSlider


This is what the SliderData component has in it:

export const SliderData = [
    {
        image: '/1.jpg',
        type: 1 
    },
    {
        image: '/2.jpg',
        type: 1
    },
    {
        image: '/3.mp4',
        type: 2
    },
    {
        image: '/5.jpg',
        type: 1
    }
];
0 Answers
Related