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.

Revisions

  1. behnamazimi created this gist Nov 8, 2020.
    42 changes: 42 additions & 0 deletions translate-x-fc.js
    Original 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>
    );
    }