import { get } from 'lodash'; import { RefObject, useEffect, useLayoutEffect, useRef } from 'react'; const AttrMap = { className: 'class', }; export function useHTMLElement( tag: string, attrs?: Record, appendTo?: HTMLElement, ): RefObject { const ref = useRef(); if (!ref.current) ref.current = document.createElement(tag); useLayoutEffect(() => { const el = ref.current; if (el && attrs) { for (const attr in attrs) { el.setAttribute(get(AttrMap, attr, attr), attrs[attr]); } return () => { for (const attr in attrs) { el.removeAttribute(get(AttrMap, attr, attr)); } }; } }, [attrs]); useEffect(() => { const el = ref.current; if (el && appendTo) { appendTo.appendChild(el); return () => el.remove(); } }, [appendTo]); return ref as RefObject; }