Last active
January 3, 2025 15:22
-
-
Save justgeek/289b57f0a042d1678c571f31166c58a5 to your computer and use it in GitHub Desktop.
React hook for viewport edge detection
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 { useEffect, useState } from 'react'; | |
export const useViewportEdgeActions = ({ element, parent, reCalculate }) => { | |
const [edgeState, setEdgeState] = useState({ | |
isCloseToRightEdge: false, | |
isCloseToLeft: false, | |
isCloseToTop: false, | |
isCloseToBottom: false, | |
}); | |
useEffect(() => { | |
if (element.current) { | |
const parentNode = parent ? parent.current : document.body; | |
const elementRect = element.current.getBoundingClientRect(); | |
const parentRect = parentNode.getBoundingClientRect(); | |
const parentRectHorizontalThreshold = Math.abs(parentRect.right - elementRect.right) - Math.abs(parentRect.left - elementRect.left); | |
const parentRectVerticalThreshold = Math.abs(parentRect.top - elementRect.top) - Math.abs(parentRect.bottom - elementRect.bottom); | |
const isCloseToRightEdge = parentRectHorizontalThreshold <= 0; | |
const isCloseToLeftEdge = parentRectHorizontalThreshold > 0; | |
const isCloseToTopEdge = parentRectVerticalThreshold <= 0; | |
const isCloseToBottomEdge = parentRectVerticalThreshold > 0; | |
setEdgeState({ isCloseToRightEdge, isCloseToLeftEdge, isCloseToTopEdge, isCloseToBottomEdge }); | |
} | |
}, [reCalculate]); | |
return edgeState; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment