Skip to content

Instantly share code, notes, and snippets.

@DZuz14
Created February 9, 2020 00:19
Show Gist options
  • Save DZuz14/519cdf00730d1935ea81baa0a404e424 to your computer and use it in GitHub Desktop.
Save DZuz14/519cdf00730d1935ea81baa0a404e424 to your computer and use it in GitHub Desktop.
Slider with React Hooks 11
/** @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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment