Created
November 8, 2020 10:37
-
-
Save behnamazimi/fe445586b8261b0dd880756d90c5d988 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, { useCallback, useEffect, useRef, useState } from "react"; | |
const intervalTime = 1000 / 60; | |
function TranslateX({ children, from, to, duration }) { | |
const [x, setX] = useState(from); | |
const lastTickRef = useRef(0); | |
useEffect(() => { | |
if (x >= to) lastTickRef.current = null; | |
}, [x]); | |
const animTick = useCallback((now) => { | |
if (lastTickRef.current === null) return; | |
if (now - lastTickRef.current >= intervalTime) { | |
const stepX = (to - from) / (duration / intervalTime); | |
setX((preX) => Math.min(to, preX + stepX)); | |
lastTickRef.current = now; | |
} | |
requestAnimationFrame(animTick); | |
}, []); | |
useEffect(() => { | |
requestAnimationFrame(animTick); | |
}, [animTick]); | |
const style = { transform: `translateX(${x}px)` }; | |
return children(style); | |
} | |
export default function App() { | |
return ( | |
<TranslateX from={0} to={500} duration={1000}> | |
{(style) => { | |
return <h1 style={style}>Translate Demo</h1>; | |
}} | |
</TranslateX> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment