Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create useFlip hook #183

Open
leroykorterink opened this issue Aug 31, 2023 · 0 comments
Open

Create useFlip hook #183

leroykorterink opened this issue Aug 31, 2023 · 0 comments
Labels
enhancement New feature or request

Comments

@leroykorterink
Copy link
Collaborator

We can use gsap Flip to animate an element between states.

useFlip(ref, {
  duration: 0.6,
  delay: 0.3,
});
import { useIsomorphicLayoutEffect, unref, Unreffable } from '@mediamonks/react-hooks';
import gsap from 'gsap';
import Flip from 'gsap/Flip';
import { useMemo, useRef, type MutableRefObject } from 'react';

gsap.registerPlugin(Flip);

export function useFlip(
  ref: Unreffable<HTMLElement | null>,
  flipStateVariables: Flip.FromToVars = {},
): MutableRefObject<Flip.FlipState | undefined> {
  const flipStateRef = useRef<Flip.FlipState>();

  const memoizedFlipStateVariables = useMemo(
    () => flipStateVariables,
    // eslint-disable-next-line react-hooks/exhaustive-deps
    Object.values(flipStateVariables),
  );

  if (typeof window !== 'undefined') {
    flipStateRef.current = Flip.getState(unref(ref));
  }

  useIsomorphicLayoutEffect(() => {
    if (flipStateRef.current === undefined) {
      return;
    }

    Flip.from(flipStateRef.current, {
      ...memoizedFlipStateVariables,
    });
  });

  return flipStateRef;
}
@leroykorterink leroykorterink added the enhancement New feature or request label Aug 31, 2023
leroykorterink added a commit that referenced this issue Oct 20, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant