Created
November 7, 2018 06:00
-
-
Save sagar-gavhane/6b8b52978206242b4b7b7e16aeee4a8d to your computer and use it in GitHub Desktop.
Observe for element resize.
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 React, { useState, useEffect, useRef, } from "react"; | |
const useElementResizer = (ref) => { | |
const [contentRect, setContentRect] = useState(ref.current ? ref.current.getBoundingClientRect() : {}); | |
useEffect(() => { | |
if (!ref.current) return; | |
const observer = new window.ResizeObserver(entries => setContentRect(entries[0].contentRect)); | |
observer.observe(ref.current); | |
return () => observer.disconnect(ref.current); | |
}, [ref]); | |
return contentRect; | |
} | |
const Component = () => { | |
const ref = useRef(null); | |
const styles = { | |
width: '50%', | |
height: '200px', | |
backgroundColor: '#2196f3', | |
margin: '0px auto', | |
padding: '25px', | |
}; | |
const { width, height, } = useElementResizer(ref); | |
return ( | |
<div> | |
<div className="box" style={styles} ref={ref}> | |
{width} x { height} | |
</div> | |
</div> | |
); | |
} | |
export default Component; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment