1
0
mirror of https://github.com/kremalicious/umami.git synced 2024-12-24 02:06:19 +01:00
umami/components/helpers/StickyHeader.js

50 lines
1.1 KiB
JavaScript
Raw Normal View History

import React, { useState, useRef, useEffect } from 'react';
import classNames from 'classnames';
export default function StickyHeader({
className,
stickyClassName,
stickyStyle,
children,
enabled = true,
}) {
const [sticky, setSticky] = useState(false);
const ref = useRef();
2020-08-12 07:29:41 +02:00
const top = useRef(0);
useEffect(() => {
const checkPosition = () => {
if (ref.current) {
2020-08-12 07:29:41 +02:00
if (!top.current) {
top.current = ref.current.offsetTop + ref.current.offsetHeight;
}
2020-08-12 07:29:41 +02:00
const state = window.pageYOffset > top.current;
if (sticky !== state) {
setSticky(state);
}
}
};
checkPosition();
if (enabled) {
window.addEventListener('scroll', checkPosition);
}
return () => {
window.removeEventListener('scroll', checkPosition);
};
}, [sticky, enabled]);
return (
<div
ref={ref}
data-sticky={sticky}
className={classNames(className, { [stickyClassName]: sticky })}
2020-08-06 04:04:02 +02:00
style={sticky ? { ...stickyStyle, width: ref?.current?.clientWidth } : null}
>
{children}
</div>
);
}