The usePerspective custom hook, utilizing framer-motion, provides a simple way to create a perspective effect on a React component. It tracks mouse movements within a designated container and adjusts the component's rotation based on the cursor position.
Importation
Make sure you have the pol-ui library installed:
import { usePerspective } from "pol-ui";
Usage
Import the usePerspective hook in your React component and apply it to the target container.
import { usePerspective } from "pol-ui";
function MyComponent() {
const {
ref,
parentWidth,
parentHeight,
x,
y,
rotateX,
rotateY,
handleMouse,
} = usePerspective();
return (
<div
ref={ref}
style={{ width: "100%", height: "100%", position: "relative" }}
onMouseMove={handleMouse}
>
<div
style={{
width: "100%",
height: "100%",
background: "lightgray",
transform: `rotateX(${rotateX}deg) rotateY(${rotateY}deg)`,
transformStyle: "preserve-3d",
transition: "transform 0.3s ease-out",
}}
>
{/* Your component content goes here */}
</div>
</div>
);
}
This example demonstrates how to use the usePerspective hook to create a perspective effect on a container based on mouse movements.
Return Value
An object with the following properties:
- ref (React.RefObject): A ref object that should be assigned to the container element.
- parentWidth (number): The width of the container element.
- parentHeight (number): The height of the container element.
- x (object): A useMotionValue instance representing the X-axis position.
- y (object): A useMotionValue instance representing the Y-axis position.
- rotateX (object): A useTransform instance for X-axis rotation.
- rotateY (object): A useTransform instance for Y-axis rotation.
- handleMouse (function): A mouse event handler to update the position based on cursor movements.
Notes
- This hook utilizes framer-motion for handling motion values and transformations.
- Adjust the styles and dimensions according to your project requirements.