react-hover-graphic
Version:
A React component to effortlessly display a graphic on hover
105 lines (103 loc) • 2.77 kB
JavaScript
"use client";
// src/components/HoverGraphic.tsx
import React, { useState, useEffect } from "react";
var HoverGraphic = ({
children,
src,
height = "auto",
// default height
width = "auto",
// default width
objectFit = "cover",
// default object-fit
zIndex = 9999,
// default z-index
offsetTop = 0,
offsetRight = 0,
offsetBottom = 0,
offsetLeft = 0,
disabled = false,
// default disabled state is false
disabledOnMobile = true
// default disabled on mobile is true
}) => {
const [position, setPosition] = useState({
x: 0,
y: 0
});
const [isVisible, setIsVisible] = useState(false);
const [isMobile, setIsMobile] = useState(false);
useEffect(() => {
const checkIfMobile = () => {
const userAgent = navigator.userAgent.toLowerCase();
const mobile = /android|webos|iphone|ipad|ipod|blackberry|windows phone/.test(
userAgent
);
setIsMobile(mobile || window.innerWidth < 768);
};
const handleScroll = () => {
if (isVisible) setIsVisible(false);
};
checkIfMobile();
window.addEventListener("resize", checkIfMobile);
window.addEventListener("scroll", handleScroll, { passive: true });
return () => {
window.removeEventListener("resize", checkIfMobile);
window.removeEventListener("scroll", handleScroll);
};
}, [isVisible]);
const handleMouseOver = (e) => {
if (!isMobile && !disabled) {
setPosition({ x: e.clientX, y: e.clientY });
setIsVisible(true);
}
};
const handleMouseOut = () => {
setIsVisible(false);
};
const handleMouseMove = (e) => {
if (isVisible) {
setPosition({ x: e.clientX, y: e.clientY });
}
};
if (disabled || disabledOnMobile && isMobile || !src) {
return /* @__PURE__ */ React.createElement(React.Fragment, null, children);
}
return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
"span",
{
onMouseOver: handleMouseOver,
onMouseOut: handleMouseOut,
onMouseMove: handleMouseMove,
style: {
cursor: "pointer",
display: "inline",
position: "relative"
}
},
children
), isVisible && /* @__PURE__ */ React.createElement(
"img",
{
src,
alt: "Hover effect",
style: {
borderRadius: "0",
border: "none",
position: "fixed",
top: `${position.y + offsetTop - offsetBottom}px`,
left: `${position.x + offsetLeft - offsetRight}px`,
height,
width,
objectFit,
transform: "translate(-50%, -50%)",
pointerEvents: "none",
zIndex
}
}
));
};
var HoverGraphic_default = HoverGraphic;
export {
HoverGraphic_default as default
};