Skip to content

Instantly share code, notes, and snippets.

@souporserious
Last active November 22, 2019 23:10
Show Gist options
  • Save souporserious/432f01856d53cb7d3d7071f5585a11f5 to your computer and use it in GitHub Desktop.
Save souporserious/432f01856d53cb7d3d7071f5585a11f5 to your computer and use it in GitHub Desktop.
ViewPager built with react-measure v4 iteration
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