Skip to content

Commit 3086e2b

Browse files
feat: add useComponentSize hook
1 parent ed46244 commit 3086e2b

File tree

5 files changed

+74
-0
lines changed

5 files changed

+74
-0
lines changed

README.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,23 @@ const YourComponent = () => {
2020
);
2121
};
2222
```
23+
24+
## useComponentSize
25+
26+
```js
27+
import { useComponentSize } from "react-use-size";
28+
29+
const YourComponent = () => {
30+
const { ref, height, width } = useComponentSize();
31+
32+
return (
33+
<React.Fragment>
34+
<div ref={ref}>
35+
Component
36+
<p>Height: {height}</p>
37+
<p>Width: {width}</p>
38+
</div>
39+
</React.Fragment>
40+
);
41+
};
42+
```

package-lock.json

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,5 +45,8 @@
4545
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS --extends @commitlint/config-conventional",
4646
"pre-commit": "npm run lint"
4747
}
48+
},
49+
"dependencies": {
50+
"resize-observer-polyfill": "1.5.1"
4851
}
4952
}

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1+
export { useComponentSize } from "./useComponentSize";
12
export { useWindowSize } from "./useWindowSize";

src/useComponentSize.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import * as React from "react";
2+
import ResizeObserver from "resize-observer-polyfill";
3+
4+
export function useComponentSize() {
5+
const [size, setSize] = React.useState({
6+
height: 0,
7+
width: 0,
8+
});
9+
const ref = React.useRef<HTMLElement>();
10+
11+
const onResize = React.useCallback(() => {
12+
if (!ref.current) {
13+
return;
14+
}
15+
16+
const newHeight = ref.current.offsetHeight;
17+
const newWidth = ref.current.offsetWidth;
18+
19+
if (newHeight !== size.height || newWidth !== size.width) {
20+
setSize({
21+
height: newHeight,
22+
width: newWidth,
23+
});
24+
}
25+
}, [ref.current]);
26+
27+
React.useLayoutEffect(() => {
28+
const element = ref.current;
29+
if (!element) {
30+
return;
31+
}
32+
33+
const resizeObserver = new ResizeObserver(() => onResize());
34+
resizeObserver.observe(element);
35+
36+
return () => {
37+
resizeObserver.disconnect();
38+
};
39+
}, [ref.current]);
40+
41+
return {
42+
ref,
43+
...size,
44+
};
45+
}

0 commit comments

Comments
 (0)