Skip to content

Commit

Permalink
Merge pull request #51 from samuelarbibe/element-ref
Browse files Browse the repository at this point in the history
fix: store timeframe ref in useState
samuelarbibe authored Aug 23, 2024
2 parents 3198660 + 4e7b3cc commit 49054e4
Showing 1 changed file with 15 additions and 16 deletions.
31 changes: 15 additions & 16 deletions packages/dnd-timeline/src/hooks/useElementRef.tsx
Original file line number Diff line number Diff line change
@@ -1,35 +1,34 @@
import { useCallback, useRef, useState } from "react";
import { type MutableRefObject, useCallback, useRef, useState } from "react";
import ResizeObserver from "resize-observer-polyfill";

export default function useElementRef() {
const ref = useRef<HTMLElement | null>(null);
const [ref, setRef] = useState<MutableRefObject<HTMLElement | null>>({
current: null,
});
const [width, setWidth] = useState(0);
const [direction, setDirection] = useState<CanvasDirection>("ltr");

const resizeObserver = useRef<ResizeObserver>();

const setRef = useCallback((element: HTMLElement | null) => {
if (element !== ref.current) {
resizeObserver.current?.disconnect();
const onSetRef = useCallback((element: HTMLElement | null) => {
resizeObserver.current?.disconnect();

if (element) {
resizeObserver.current = new ResizeObserver((entries) => {
for (const entry of entries) {
setWidth(entry.contentRect.width);
}
});
if (element) {
resizeObserver.current = new ResizeObserver((entries) => {
setWidth(entries[0].contentRect.width);
});

resizeObserver.current.observe(element);
resizeObserver.current.observe(element);

setDirection(getComputedStyle(element).direction as CanvasDirection);
}
setDirection(getComputedStyle(element).direction as CanvasDirection);
}
ref.current = element;

setRef({ current: element });
}, []);

return {
ref,
setRef,
setRef: onSetRef,
width,
direction,
};

0 comments on commit 49054e4

Please sign in to comment.