I have created a Hoverable Image component in React with the Framer Motion library. The component works perfectly when tested locally, but when I try to use it in Framer, the image does not display.
I have checked that the component is imported correctly and that all the necessary props are being passed. I have also checked the console for any errors, but there are none.
import { useState, useRef } from "react"
import { motion } from "framer-motion"
export default function HoverableImage(props) {
const { style } = props
const [isHovered, setIsHovered] = useState(false)
const [cursorPosition, setCursorPosition] = useState({ x: 0, y: 0 })
const divRef = useRef(null)
const handleMouseMove = (event) => {
const rect = divRef.current.getBoundingClientRect()
const x = event.clientX - rect.left
const y = event.clientY - rect.top
setCursorPosition({ x, y })
}
const handleMouseLeave = () => {
setIsHovered(false)
}
const handleMouseEnter = () => {
setIsHovered(true)
}
const isCursorInside = () => {
if (!divRef.current) return false
const rect = divRef.current.getBoundingClientRect()
const { x, y } = cursorPosition
return (
x >= rect.left &&
x <= rect.right &&
y >= rect.top &&
y <= rect.bottom
)
}
return (
<motion.div
ref={divRef}
style={{
position: "absolute",
height: "70px",
width: "100%",
zIndex: 1,
...style,
}}
onMouseMove={handleMouseMove}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
whileHover={{ cursor: "pointer" }}
>
{isHovered && isCursorInside() && (
<motion.img
src="https://images.pexels.com/photos/12629063/pexels-photo-12629063.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
alt="image"
style={{
position: "absolute",
top: cursorPosition.y,
left: cursorPosition.x,
transform: "translate(-50%, -50%)",
width: "100px",
height: "100px",
zIndex: 1,
opacity: isHovered ? 1 : 0,
transition: "opacity 0.2s ease-out",
pointerEvents: isHovered ? "auto" : "none",
display: isHovered ? "flex" : "none",
}}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
/>
)}
</motion.div>
)
}
HoverableImage.defaultProps = {
style: {},
}
Working in preview Not working in my Browser
Does anyone have any suggestions for why the image is not displaying in Framer? Any help would be greatly appreciated.
The expected behavior of the hoverable image component is that when the user hovers over the parent div, the image should be displayed centered around the cursor position. The image should disappear when the user moves the cursor away from the parent div. The hoverable image component should also have smooth transitions and animations when it appears and disappears.