You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
import{typeMutableRefObject,useEffect,useId}from'react';/** * This hook generates an id for a component and then watches the DOM mutations to find it as soon as it's loaded. This * is commonly used for lazy loaded components. */exportfunctionuseDynamicComponentRef(ref: MutableRefObject<unknown>): string{constid=useId();useEffect(()=>{constmutationObserver=newMutationObserver(()=>{ref.current=document.querySelector(`[data-id="${id}"]`);if(ref.current){mutationObserver.disconnect();}});mutationObserver.observe(// TODO: This could be the parent element of the dynasmic component to reduce the amount of DOM mutations being observed.document.body,{childList: true,// NOTE: If we only allow to use this hook on the parent element of dynamic component we can set this to false.subtree: true,},);return(): void=>{mutationObserver.disconnect();};// eslint-disable-next-line react-hooks/exhaustive-deps},[id]);returnid;}
The text was updated successfully, but these errors were encountered:
import{useEffect,useId,typeMutableRefObject,typeRefObject}from'react';/** * This hook generates an id for a component and then watches the DOM mutations to find it as soon as it's loaded. This * is commonly used for lazy loading SVGs into the application. Just make sure to assign the returned id value to * the `data-id` on the lazy loaded component. * * @param ref */exportfunctionuseDynamicComponentRef(ref: MutableRefObject<Element|null>,parent: RefObject<Element>,): string{constid=useId();useEffect(()=>{if(parent.current===null){thrownewError("The parent element can't be null");}constmutationObserver=newMutationObserver(()=>{ref.current=document.querySelector(`[data-id="${id}"]`);if(ref.current){mutationObserver.disconnect();}});mutationObserver.observe(parent.current,{childList: true,});return(): void=>{mutationObserver.disconnect();};// eslint-disable-next-line react-hooks/exhaustive-deps},[id]);returnid;}
A common use case for getting refs for lazy components, so do something with them as soon as they are loaded. For example, to add them to dependencies of useEffect to update the animation, etc.
The downside of using a ref for this, is that you won't be notified of any changes.
Can we document use cases for this hook, so we know if the parent is always available. And if it is, to check if we don't have an easier way to detect if it's loaded, for example when we have direct access to the element and can use the onLoad or something similar.
leroykorterink
changed the title
Create useDynamicComponentRef hook
Create useDynamicComponentRef hook
Mar 28, 2023
The text was updated successfully, but these errors were encountered: