Creating a slider with React hooks that slides through an array on an interval.
We had a need for an auto advancing image slider in React. I chose to use hooks for this feature. This hook leverages a useInterval
hook from Dan Abrimov.
What We’re Building TL;DR
Requirements
This component needs do a few things.
- Should accept an slide array
- Should accept a duration in milliseconds
- Should animate between slides
- Should move through array on it’s own
useInterval
Here’s the useInterval
code.
Setting an interval can be problematic in JavaScript, mostly because of cleanup (or lack of). With useEffect
we get a nice cleanup with the return function, return () => clearInterval(id);
.
useSlider
Now that we have that set up we can leverage it to help us with timing.
Slider Component
Our slider component adds all slides next to each other and moves the .scroller
(absolutely positioned) through the .container
(relatively positioned). This allows us to animate between the slides. Here’s the stateless structure of our component.
Putting it All Together
Now we can add our hook to our slider component. This will give us all the state that we’ll need for this feature. When it’s all together we get a slider that moves the slides horizontally and rewinds after the last one. You can hook up the slider props to manage the slider options if needed. It can also be made to go vertical with a little modification.
Cool! Requirements met.
- Should accept an slide array
- Should accept a duration in milliseconds
- Should animate between slides
- Should move through array on it’s own