@pras-ui/presence
v1.0.1
Published
> A low-level, headless hook for managing component presence to allow for animations on mount and unmount.
Downloads
10
Readme
@pras-ui/presence
A low-level, headless hook for managing component presence to allow for animations on mount and unmount.
This package provides a usePresence hook that delays unmounting a component until its exit animation has completed. It's a critical utility for building animated components like dialogs, popups, and tooltips.
Installation
npm install @pras-ui/presenceUsage
The usePresence hook is used to conditionally render a component while allowing for exit animations.
It takes a boolean present prop and returns isPresent (a boolean) and a ref that must be attached to the element you want to animate.
isPresent: A boolean that remainstrueduring the exit animation, then becomesfalse. Use this to conditionally render your component.ref: The ref to attach to your animated element.
Here is a basic example of a component that fades in and out.
Component
import React from "react";
import { usePresence } from "@pras-ui/presence";
import "./styles.css"; // Make sure to create and import your CSS
interface FadeInProps {
open: boolean;
children?: React.ReactNode;
}
function FadeIn({ open, children }: FadeInProps) {
const { isPresent, ref } = usePresence(open);
return isPresent ? (
<div ref={ref} data-state={open ? "open" : "closed"}>
{children}
</div>
) : null;
}CSS for Animations
You can use the data-state attribute to apply your animations.
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes fadeOut {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
[data-state="open"] {
animation: fadeIn 900ms ease-out;
}
[data-state="closed"] {
animation: fadeOut 900ms ease-in;
}Example Implementation
function App() {
const [show, setShow] = React.useState(false);
return (
<>
<button onClick={() => setShow(!show)}>Toggle</button>
<FadeIn open={show}>
<div>Hello World</div>
</FadeIn>
</>
);
}