Created
November 6, 2019 15:40
-
-
Save beve/77af0e473d45e4ebc3fb0daac9c623f6 to your computer and use it in GitHub Desktop.
Not optimized react hook to check collision between two elements
This file contains hidden or 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 { useState, useEffect, useCallback } from "react" | |
| export default function useCollision(ref1, ref2) { | |
| const [overlap, setOverlap] = useState(null) | |
| const scrollHandler = useCallback(() => { | |
| var rect1 = | |
| ref1.current instanceof Element | |
| ? ref1.current.getBoundingClientRect() | |
| : false | |
| var rect2 = | |
| ref2.current instanceof Element | |
| ? ref2.current.getBoundingClientRect() | |
| : false | |
| if (!rect1 || !rect2) { | |
| return | |
| } | |
| const olp = !( | |
| rect1.right < rect2.left || | |
| rect1.left > rect2.right || | |
| rect1.bottom < rect2.top || | |
| rect1.top > rect2.bottom | |
| ) | |
| if (olp !== overlap) { | |
| setOverlap(olp) | |
| } | |
| }, [ref1, ref2, overlap]) | |
| useEffect(() => { | |
| scrollHandler(); | |
| window.addEventListener("scroll", scrollHandler, true); | |
| return () => { | |
| window.removeEventListener("scroll", scrollHandler); | |
| } | |
| }, [scrollHandler]) | |
| return overlap | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment