Last active
November 22, 2019 23:10
-
-
Save souporserious/432f01856d53cb7d3d7071f5585a11f5 to your computer and use it in GitHub Desktop.
ViewPager built with react-measure v4 iteration
This file contains hidden or 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, { useRef } from 'react' | |
import { useMeasure } from 'react-measure' | |
function getViewTargets(node) { | |
const targets = [] | |
if (node) { | |
let target = 0 | |
for (let index = 0; index < node.children.length; index++) { | |
const childNode = node.children[index] | |
const bounds = childNode.getBoundingClientRect() | |
targets.push(target) | |
target -= bounds.width | |
} | |
} | |
return targets | |
} | |
function ViewPager({ activeViewIndex, children }) { | |
const trackRef = useRef() | |
const viewTargets = useMeasure(trackRef, getViewTargets) | |
return ( | |
<div style={{ overflow: 'hidden' }}> | |
<div | |
ref={trackRef} | |
style={{ | |
transform: `translateX(${viewTargets[activeViewIndex]}px)`, | |
transition: 'transform ease-out' | |
}} | |
> | |
{children} | |
</div> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment