mirror of
https://git.rdcenter.ru/RDCenter/skb-kit.git
synced 2026-12-05 03:09:45 +00:00
Стили для проектов, хук для динамического размера
This commit is contained in:
1 parent
f22179654b
commit
3b201e8a8b
5 files changed
+196
-154
No files matched your search
@@ -0,0 +1,41 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
type ResizeHandler = (parent: HTMLElement, childHeight: number) => void;
|
||||
|
||||
interface UseResizeObserverConfig {
|
||||
parentSelector: string;
|
||||
childSelector?: string;
|
||||
onResize?: ResizeHandler;
|
||||
}
|
||||
|
||||
export const useResizeObserver = ({
|
||||
parentSelector,
|
||||
childSelector = 'blockquote',
|
||||
onResize = (parent, height) => {
|
||||
parent.style.marginBottom = `calc(${height}px + 2em)`;
|
||||
}
|
||||
}: UseResizeObserverConfig) => {
|
||||
useEffect(() => {
|
||||
const resizeObserver = new ResizeObserver(entries => {
|
||||
entries.forEach(entry => {
|
||||
const parent = entry.target as HTMLElement;
|
||||
const child = parent.querySelector(childSelector) as HTMLElement | null;
|
||||
|
||||
if (child) {
|
||||
const childHeight = child.offsetHeight;
|
||||
onResize(parent, childHeight);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const elements = document.querySelectorAll(parentSelector);
|
||||
const elementsArray = Array.from(elements) as HTMLElement[];
|
||||
|
||||
elementsArray.forEach(element => resizeObserver.observe(element));
|
||||
|
||||
return () => {
|
||||
elementsArray.forEach(element => resizeObserver.unobserve(element));
|
||||
resizeObserver.disconnect();
|
||||
};
|
||||
}, [parentSelector, childSelector, onResize]);
|
||||
};
|
||||
Reference in new issue
Block a user