Created
June 17, 2019 12:41
-
-
Save MohitTilwani15/d915e10e08ae0a145fea8cbd212f6fc1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, FunctionComponent } from 'react'; | |
import styled from 'styled-components'; | |
const Wrapper = styled.div` | |
width: 100%; | |
overflow: hidden; | |
`; | |
const CarouselContainer = styled.div<StyledCarouselContainerProps>` | |
display: flex; | |
margin: 0 0 2rem 2rem; | |
transition: ${props => props.sliding ? 'none' : 'transform 1s ease'}; | |
transform: ${props => { | |
if (!props.sliding) return 'translateX(calc(-80% - 20px))'; | |
return props.direction === 'prev' ? 'translateX(calc(2 * (-80% - 20px)))' : 'translateX(0%)'; | |
}}; | |
`; | |
const CarouselSlot = styled.div<StyledCarouselSlotProps>` | |
flex: 1 0 100%; | |
flex-basis: 80%; | |
margin-right: 2rem; | |
order: ${props => props.order}; | |
`; | |
type RSliderProps = { | |
children: React.ReactNodeArray, | |
}; | |
type StyledCarouselContainerProps = { | |
sliding: boolean, | |
direction: string, | |
}; | |
type StyledCarouselSlotProps = { | |
order: number, | |
}; | |
const RSlider: FunctionComponent<RSliderProps> = (props: RSliderProps) => { | |
const [position, setPosition] = useState(0); | |
const [sliding, setSliding] = useState(false); | |
const [direction, setDirection] = useState('next'); | |
const renderItems = (): React.ReactNodeArray => { | |
return props.children.map((child: React.ReactNode, idx: number) => { | |
return ( | |
<CarouselSlot key={idx} order={getOrder(idx)}> | |
{child} | |
</CarouselSlot> | |
); | |
}); | |
}; | |
const getOrder = (itemIndex: number): number => { | |
const numItems = props.children.length || 1; | |
return (itemIndex - position < 0) ? numItems - Math.abs(itemIndex - position) : itemIndex - position; | |
}; | |
const nextSlide = (): void => { | |
const numItems = props.children.length || 1; | |
doSliding('next', position === numItems - 1 ? 0 : position + 1); | |
}; | |
const prevSlide = (): void => { | |
const numItems = props.children.length || 1; | |
doSliding('prev', position === 0 ? numItems - 1 : position - 1); | |
}; | |
const doSliding = (direction: string, position: number): void => { | |
setSliding(true); | |
setPosition(position); | |
setDirection(direction); | |
setTimeout(() => { | |
setSliding(false); | |
}, 50); | |
}; | |
return ( | |
<> | |
<Wrapper> | |
<CarouselContainer direction={direction} sliding={sliding}> | |
{renderItems()} | |
</CarouselContainer> | |
</Wrapper> | |
<button onClick={prevSlide}>Prev</button> | |
<button onClick={nextSlide}>Next</button> | |
</> | |
); | |
}; | |
export default React.memo(RSlider); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment