Skip to content

Instantly share code, notes, and snippets.

@dance2die
Last active August 22, 2019 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dance2die/4483589c5ff5ed9cc9a6fc9ecd2588be to your computer and use it in GitHub Desktop.
Save dance2die/4483589c5ff5ed9cc9a6fc9ecd2588be to your computer and use it in GitHub Desktop.
function Sticky({ children, as = "div", className = "", ...rest }) {
// 1️⃣ Get TOP & BOTTOM sentinels to associate with
const { topSentinelRef, bottomSentinelRef } = useContext(
StickySectionContext
);
const dispatch = useStickyActions();
// 2️⃣ Associate the current element with TOP & BOTTOM sentinels
// so that we can retrieve correct child target element
// from either a top sentinel or a bottom sentinel
const addStickyRef = stickyRef => {
dispatch.addStickyRef(topSentinelRef, bottomSentinelRef, stickyRef);
};
const Component = as;
// 3️⃣ No magic - Just apply the "sticky" position using class
return (
<Component
ref={addStickyRef}
className={styles.sticky + className || ` ${className}`}
{...rest}
>
{children}
</Component>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment