Skip to content

Commit

Permalink
[@mantine/hooks] use-mutation-observer: Init hook
Browse files Browse the repository at this point in the history
  • Loading branch information
rtivital committed Mar 4, 2024
1 parent 28683f2 commit a0850de
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React from 'react';
import { useInterval } from '@mantine/hooks';
import { FloatingIndicator } from './FloatingIndicator';

export default { title: 'FloatingIndicator' };
Expand Down Expand Up @@ -75,3 +76,35 @@ export function ResizableTarget() {
</div>
);
}

export function ScaledElement() {
const [targetRef, setTargetRef] = React.useState<HTMLDivElement | null>(null);
const [parentRef, setParentRef] = React.useState<HTMLDivElement | null>(null);
const [scale, setScale] = React.useState(1);
const interval = useInterval(() => setScale(Math.random()), 500);

React.useEffect(() => {
interval.start();
}, []);

return (
<div style={{ padding: 40 }}>
<div ref={(node) => setParentRef(node!)} style={{ position: 'relative' }}>
<div
ref={(node) => setTargetRef(node!)}
style={{
padding: 20,
background: 'pink',
width: 200,
height: 200,
transition: 'transform 100ms',
transform: `scale(${scale})`,
}}
>
Resizable target
</div>
<FloatingIndicator target={targetRef} parent={parentRef} />
</div>
</div>
);
}
1 change: 1 addition & 0 deletions packages/@mantine/hooks/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export { useFavicon } from './use-favicon/use-favicon';
export { useHeadroom } from './use-headroom/use-headroom';
export { useEyeDropper } from './use-eye-dropper/use-eye-dropper';
export { useInViewport } from './use-in-viewport/use-in-viewport';
export { useMutationObserver } from './use-mutation-observer/use-mutation-observer';

export type { UseMovePosition } from './use-move/use-move';
export type { OS } from './use-os/use-os';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { RefObject, useEffect, useRef } from 'react';

export function useMutationObserver<Element extends HTMLLIElement>(
callback: MutationCallback,
options: MutationObserverInit,
target?: HTMLElement | (() => HTMLElement) | null
) {
const observer = useRef<MutationObserver>();
const ref: RefObject<Element> = useRef(null);

useEffect(() => {
const targetElement = typeof target === 'function' ? target() : target;

if (targetElement || ref.current) {
observer.current = new MutationObserver(callback);
observer.current.observe(targetElement || ref.current!, options);
}

return () => {
observer.current?.disconnect();
};
}, [callback, options]);

return ref;
}

0 comments on commit a0850de

Please sign in to comment.