Files
base/node_modules/svelte-toolbelt/dist/utils/use-ref-by-id.svelte.js
T
eewing ec317eb17c
CI / build (push) Has been skipped
CI / deploy (push) Successful in 1m11s
INIT
2026-02-18 15:17:47 -06:00

23 lines
757 B
JavaScript

import { watch } from "runed";
import { onDestroyEffect } from "./on-destroy-effect.svelte.js";
/**
* Finds the node with that ID and sets it to the boxed node.
* Reactive using `$effect` to ensure when the ID or deps change,
* an update is triggered and new node is found.
*/
export function useRefById({ id, ref, deps = () => true, onRefChange, getRootNode }) {
watch([() => id.current, deps], ([_id]) => {
const rootNode = getRootNode?.() ?? document;
const node = rootNode?.getElementById(_id);
if (node)
ref.current = node;
else
ref.current = null;
onRefChange?.(ref.current);
});
onDestroyEffect(() => {
ref.current = null;
onRefChange?.(null);
});
}