Skip to content

Commit

Permalink
refact: convert react-swipeable to use hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
veksen committed Mar 11, 2020
1 parent ddfe315 commit 640c20a
Showing 1 changed file with 33 additions and 31 deletions.
64 changes: 33 additions & 31 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as React from 'react';
import ReactResizeDetector from 'react-resize-detector';
import { EventData, Swipeable, SwipeableOptions } from 'react-swipeable';
import { useSwipeable, EventData, SwipeableOptions } from 'react-swipeable';
import { Arrow } from './arrow';

import {
Expand Down Expand Up @@ -42,6 +42,19 @@ const Swiper = ({
const [lastSwipe, setLastSwipe] = React.useState<number | null>(null);
const [width, setWidth] = React.useState<number>(0);

const swipeConfig: SwipeableOptions = {
trackTouch: true,
trackMouse: true,
};

const swipeHandlers = useSwipeable({
onSwiping: eventData => onSwiping(eventData),
onSwiped: () => {
setSlideOffset(0);
},
...swipeConfig,
});

const computeMedia = () => {
if (width <= MEDIA_MAX_XS) {
return 'xs';
Expand Down Expand Up @@ -129,20 +142,11 @@ const Swiper = ({
}
};

const onSwipeEnd = () => {
setSlideOffset(0);
};

const onResize = (w: number) => {
setWidth(w);
resetSwipe();
};

const swipeConfig: SwipeableOptions = {
trackTouch: true,
trackMouse: true,
};

const hideArrows = items.length <= itemsWide;

return (
Expand All @@ -159,28 +163,26 @@ const Swiper = ({
<Arrow />
</ArrowLeft>
)}
<Swipeable
onSwiping={eventData => onSwiping(eventData)}
onSwiped={onSwipeEnd}
{...swipeConfig}
<SwiperCanvas
{...swipeHandlers}
className={canvasClassName}
style={canvasStyle}
>
<SwiperCanvas className={canvasClassName} style={canvasStyle}>
{items.map((item, i) => (
<Item
key={i}
itemsWide={computeItemWidth()}
currentIndex={currentIndex}
data-testid="item"
style={{
left: `-${(currentIndex * 100) / computeItemWidth() +
slideOffset}%`,
}}
>
{item}
</Item>
))}
</SwiperCanvas>
</Swipeable>
{items.map((item, i) => (
<Item
key={i}
itemsWide={computeItemWidth()}
currentIndex={currentIndex}
data-testid="item"
style={{
left: `-${(currentIndex * 100) / computeItemWidth() +
slideOffset}%`,
}}
>
{item}
</Item>
))}
</SwiperCanvas>
{!hideArrows && (
<ArrowRight
data-testid="next"
Expand Down

0 comments on commit 640c20a

Please sign in to comment.