mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
chore: move all the tests to the separate directory outside of sources; chore: remove jest.config.js (config moved to the package.json); test: unused import in test; test: 💍 fix tests add back x and y to useMeasure chore: 🤖 add linter to /tests folder ci: 🎡 limit Jest worker count for CircleCI
41 lines
848 B
TypeScript
41 lines
848 B
TypeScript
import { useCallback, useState } from 'react';
|
|
import ResizeObserver from 'resize-observer-polyfill';
|
|
|
|
export type ContentRect = Pick<DOMRectReadOnly, 'x' | 'y' | 'top' | 'left' | 'right' | 'bottom' | 'height' | 'width'>;
|
|
|
|
const useMeasure = <T>(): [(instance: T) => void, ContentRect] => {
|
|
const [rect, set] = useState<ContentRect>({
|
|
x: 0,
|
|
y: 0,
|
|
width: 0,
|
|
height: 0,
|
|
top: 0,
|
|
left: 0,
|
|
bottom: 0,
|
|
right: 0,
|
|
});
|
|
|
|
const [observer] = useState(
|
|
() =>
|
|
new ResizeObserver(entries => {
|
|
const entry = entries[0];
|
|
if (entry) {
|
|
set(entry.contentRect);
|
|
}
|
|
})
|
|
);
|
|
|
|
const ref = useCallback(
|
|
node => {
|
|
observer.disconnect();
|
|
if (node) {
|
|
observer.observe(node);
|
|
}
|
|
},
|
|
[observer]
|
|
);
|
|
return [ref, rect];
|
|
};
|
|
|
|
export default useMeasure;
|