Skip to content

Instantly share code, notes, and snippets.

@LeeCheneler
Last active February 4, 2022 11:21
Show Gist options
  • Save LeeCheneler/c43281e2fc1bc51fcb298d8b49c513c7 to your computer and use it in GitHub Desktop.
Save LeeCheneler/c43281e2fc1bc51fcb298d8b49c513c7 to your computer and use it in GitHub Desktop.
React hook to track whether an element is on the screen
import "jest";
import React from "react";
let externalSetShouldLoadMore = null;
export const usePaginationTrigger = () => {
const [shouldLoadMore, setShouldLoadMore] = React.useState(false);
externalSetShouldLoadMore = setShouldLoadMore;
return shouldLoadMore;
};
export const triggerPagination = () => {
if (externalSetShouldLoadMore) {
externalSetShouldLoadMore(true);
setTimeout(() => {
externalSetShouldLoadMore(false);
});
}
};
//then in tests you do something like:
import { triggerPagination } from "../../hooks/use-pagination-trigger";
...
act(() => {
triggerPagination();
});
...
import React from "react";
export const usePaginationTrigger = (
ref: React.MutableRefObject<undefined>
) => {
const [shouldLoadMore, setShouldLoadMore] = React.useState(false);
React.useEffect(() => {
let observer: IntersectionObserver | null = null;
observer = new IntersectionObserver(([entry]) =>
setShouldLoadMore(entry.isIntersecting)
);
observer.observe(ref.current);
return () => {
observer.disconnect();
};
}, [ref]);
return shouldLoadMore;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment