Skip to content

Instantly share code, notes, and snippets.

@behnamazimi
Created November 8, 2020 10:37
Show Gist options
  • Save behnamazimi/fe445586b8261b0dd880756d90c5d988 to your computer and use it in GitHub Desktop.
Save behnamazimi/fe445586b8261b0dd880756d90c5d988 to your computer and use it in GitHub Desktop.
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