A small hook to check dimension of a DOM ELement or Window when a browser window is resized.
Coming Soon!
Using npm
$ npm install @shubhaemk/use-element-resize
Using yarn
$ yarn add @shubhaemk/use-element-resize
- Get Height and Width of a DOM Element when browser window is resized.
- Execute a function when browser window is resized. (Do not use it to set Height and Width of element in state, use useEffect hook instead till it gets option to be throttled)
- Server Side Rendering support. (Needs to be tested)
- Throttling of Callback function. (Comming Soon!)
const [height, width] = useElementResize(ref, callback);
height
(Default: undefined): Height of given Element reference or window inpx
,undefined
till Element is completely painted.width
(Default: undefined): Width if given Element reference or window inpx
,undefined
till Element is completely painted.ref
(Default: window): Ref of element to whose height and width are required after window resize.callback
: Callback function to be executed after each window resize. (Throttling comming soon)
import { useRef } from "react";
import useElementResize from "use-element-resize";
const ElementSizeExample = () => {
const ElementRef = useRef();
// height and width of browser window
const [windowHeight, windowWidth] = useElementResize();
// height and width of browser window with execution of a callback
const [windowHeightCallback, windowWidthCallback] = useElementResize(
null,
() => {
console.log("Browser Window is getting resized");
}
);
// height and width of DOM Element reffered by ElementRef
const [elementHeight, elementWidth] = useElementResize(ElementRef);
// height and width of DOM Element reffered by ElementRef with execution of a callback
const [elementHeightCallback, elementWidthCallback] = useElementResize(
ElementRef,
() => {
console.log("Element is getting resized");
}
);
return <div style={{ width: "100%", height: "50px" }} ref={ElementRef}></div>;
};
- Throttling of callback function.
- TypeScript implementation ✅