import { useEffect, useRef } from "react";
const FloatingComponent = () => {
const componentRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const bottomOffset = 20;
const handleScroll = () => {
if (!componentRef.current) return;
const viewportHeight = window.innerHeight;
const elementHeight = componentRef.current.offsetHeight;
const scrollY = window.scrollY;
const topOffset = viewportHeight - bottomOffset - elementHeight - scrollY;
//center position
const centerY = (viewportHeight - elementHeight) / 2;
// set the component top position
componentRef.current.style.top = `${Math.max(centerY, topOffset)}px`;
};
window.addEventListener("scroll", handleScroll);
window.addEventListener("resize", handleScroll);
handleScroll();
return () => {
window.removeEventListener("scroll", handleScroll);
window.removeEventListener("resize", handleScroll);
};
}, []);
return (
<div
ref={componentRef}
style={{
backgroundColor: "black",
color: "white",
width: "fit-content",
padding: "2rem",
borderRadius: "2rem",
position: "fixed",
right: "20px",
}}
>
Floating Component
</div>
);
};
export default FloatingComponent;
import { useEffect, useRef } from "react";
const FloatingComponent = () => {
const componentRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const bottomOffset = 20;
const handleScroll = () => {
if (!componentRef.current) return;
const viewportHeight = window.innerHeight;
const elementHeight = componentRef.current.offsetHeight;
const scrollY = window.scrollY;
const topOffset = viewportHeight - bottomOffset - elementHeight - scrollY;
//center position
const centerY = (viewportHeight - elementHeight) / 2;
// set the component top position
componentRef.current.style.top = `${Math.max(centerY, topOffset)}px`;
};
window.addEventListener("scroll", handleScroll);
window.addEventListener("resize", handleScroll);
handleScroll();
return () => {
window.removeEventListener("scroll", handleScroll);
window.removeEventListener("resize", handleScroll);
};
}, []);
return (
<div
ref={componentRef}
style={{
backgroundColor: "black",
color: "white",
width: "fit-content",
padding: "2rem",
borderRadius: "2rem",
position: "fixed",
right: "20px",
}}
>
Floating Component
</div>
);
};
export default FloatingComponent;