Created
November 8, 2020 10:37
-
-
Save behnamazimi/fe445586b8261b0dd880756d90c5d988 to your computer and use it in GitHub Desktop.
Revisions
-
behnamazimi created this gist
Nov 8, 2020 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,42 @@ 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> ); }