Skip to content

Instantly share code, notes, and snippets.

@JoviDeCroock
Last active October 3, 2020 12:10
Show Gist options
  • Save JoviDeCroock/6b8ec847bd2235fbfb46addbd0878095 to your computer and use it in GitHub Desktop.
Save JoviDeCroock/6b8ec847bd2235fbfb46addbd0878095 to your computer and use it in GitHub Desktop.
const AnimateMountUnmount = ({ mountClass, unmountClass }) => {
const [mounted, setMounted] = useState(false);
const [unmounting, setUnmounting] = useState(false);
// Can also be attached with useImperativeHandle to the parent.
const unmountSignal = () => {
setUnmounting(true)
}
useEffect(() => {
setTimeout(() => {
setMounted(true);
}, animationDuration)
}, []);
return <Component className={mounted ? '' : mountClass + ' ' + unmounting ? unmountClass : ''} unmount={unmountSignal} />
}
import { useState, useLayoutEffect, useCallback } from 'preact/hooks';
interface UseMountUnmountArguments {
mountingClass: string;
unmountingClass: string;
duration: number;
};
type UseMountUnmountValues = [string, boolean, () => void];
export const useMountUnmount = ({ mountingClass, unmountingClass, duration }: UseMountUnmountArguments): UseMountUnmountValues => {
const [mounted, setMounted] = useState(false);
const [isMounting, setIsMounting] = useState(false);
const [isUnmounting, setIsUnmounting] = useState(false);
// Can also be attached with useImperativeHandle to the parent.
const unmount = useCallback(() => {
setIsUnmounting(true);
setTimeout(() => {
setIsUnmounting(false);
setMounted(false);
}, duration);
}, []);
useLayoutEffect(() => {
setIsMounting(true);
setTimeout(() => {
setIsMounting(false);
setMounted(true);
}, duration);
}, []);
return [
isMounting ? mountingClass : isUnmounting ? unmountingClass : '',
mounted,
unmount
]
}
import { useState, useEffect } from 'preact/hooks';
interface UseSpringProps {
lazy?: boolean;
from?: number;
to: number;
property: string;
duration: number;
}
const lerp = (from: number, to: number, fraction: number) => (to - from) * fraction + from;
export const useSpring = ({ lazy, from, to, duration, property }: UseSpringProps) => {
const [isActivated, setIsActivated] = useState(!lazy);
const [value, setValue] = useState<number>(from || 0);
useEffect(() => {
if (isActivated) {
setValue(lerp(value, to, (to - (from || 0) / duration)));
}
}, [isActivated]);
return [
{ [property]: value },
setIsActivated,
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment