Last active
February 4, 2022 11:21
-
-
Save LeeCheneler/c43281e2fc1bc51fcb298d8b49c513c7 to your computer and use it in GitHub Desktop.
React hook to track whether an element is on the screen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//then in tests you do something like: | |
import { triggerPagination } from "../../hooks/use-pagination-trigger"; | |
... | |
act(() => { | |
triggerPagination(); | |
}); | |
... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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