react-use/src/useMeasure.ts
Anton Zinovyev 8de2a3ee13 chore: move tests to top level /tests folder
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
2019-11-08 16:55:34 -05:00

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;