Created
April 7, 2019 09:52
-
-
Save kevinfelisilda/fce9e14f8c155728274ba2daf04a7387 to your computer and use it in GitHub Desktop.
hook for triggering callback on browser resize
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'; | |
/** | |
* Usage: | |
* | |
* const ref = useRef(); | |
* | |
* useResize(ref, (data) => { | |
* console.log(data.width); | |
* }); | |
* | |
* return ( | |
* <div ref={ref}> | |
* The content | |
* </div> | |
* ); | |
*/ | |
const useResize = (ref, callback, defaultValue = {}) => { | |
const [initialize, setInitialized] = useState(false); | |
const getValue = () => { | |
const target = ref && ref.current; | |
if (!target) { | |
return defaultValue; | |
} | |
return { | |
height: target.offsetHeight, | |
width: target.offsetWidth, | |
x: target.offsetLeft, | |
y: target.offsetTop, | |
target | |
}; | |
} | |
const onResize = () => { | |
if ('function' === typeof callback) { | |
callback(getValue()); | |
} | |
} | |
useEffect(() => { | |
window.addEventListener('resize', onResize); | |
if (!initialize) { | |
onResize(); | |
setInitialized(true); | |
} | |
return () => { | |
window.removeEventListener('resize', onResize); | |
} | |
}) | |
} | |
export const useResize; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment