In this second part of the React Hooks Slider series, we are now going to build an autoplay feature into our component. When activated, this feature will hide the navigation arrows and cycle through all of the image slides in an infinite loop.
I have included links at the end of this article to the first and third parts of the series, the repository that includes the code and a working example, and a video tutorial.
At the end of Part 1, this is the code we ended up with in our Slider
component.
/** @jsx jsx */
import React, { useState, useEffect, useRef } from 'react'
import { css, jsx } from '@emotion/core'
import SliderContent from './SliderContent'
import Slide from './Slide'
import Arrow from './Arrow'
import Dots from './Dots'
/**
* @function Slider
*/
const Slider = props => {
const getWidth = () => window.innerWidth
const [state, setState] = useState({
activeIndex: 0,
translate: 0,
transition: 0.45
})
const { translate, transition, activeIndex } = state
const nextSlide = () => {
if (activeIndex === props.slides.length - 1) {
return setState({
...state,
translate: 0,
activeIndex: 0
})
}
setState({
...state,
activeIndex: activeIndex + 1,
translate: (activeIndex + 1) * getWidth()
})
}
const prevSlide = () => {
if (activeIndex === 0) {
return setState({
...state,
translate: (props.slides.length - 1) * getWidth(),
activeIndex: props.slides.length - 1
})
}
setState({
...state,
activeIndex: activeIndex - 1,
translate: (activeIndex - 1) * getWidth()
})
}
return (
<div css={SliderCSS}>
<SliderContent
translate={translate}
transition={transition}
width={getWidth() * props.slides.length}
>
{props.slides.map((slide, i) => (
<Slide key={slide + i} content={slide} />
))}
</SliderContent>
<Arrow direction="left" handleClick={prevSlide} />
<Arrow direction="right" handleClick={nextSlide} />
<Dots slides={props.slides} activeIndex={activeIndex} />
</div>
)
}
const SliderCSS = css`
position: relative;
height: 100vh;
width: 100vw;
margin: 0 auto;
overflow: hidden;
`
export default Slider
#web-development #front-end-development #javascript #react #programming #react hooks