diff --git a/components/lib/hooks/useStyle.js b/components/lib/hooks/useStyle.js index 1b4a89313d..af29ceba28 100644 --- a/components/lib/hooks/useStyle.js +++ b/components/lib/hooks/useStyle.js @@ -12,16 +12,33 @@ export const useStyle = (css, options = {}) => { const defaultDocument = DomHandler.isClient() ? window.document : undefined; const { document = defaultDocument, manual = false, name = `style_${++_id}`, id = undefined, media = undefined } = options; + const getCurrentStyleRef = (styleContainer) => { + const existingStyleContainerChild = styleContainer.querySelector(`style[data-primereact-style-id="${name}"]`); + + if (existingStyleContainerChild) { + return existingStyleContainerChild; + } + + if (id !== undefined) { + const existingElementWithId = document.getElementById(id); + + if (existingElementWithId) { + return existingElementWithId; + } + } + + return document.createElement('style'); + }; + const update = (newCSS) => { isLoaded && css !== newCSS && (styleRef.current.textContent = newCSS); }; const load = () => { if (!document || isLoaded) return; - const styleContainer = context?.styleContainer || document.head; - styleRef.current = styleContainer.querySelector(`style[data-primereact-style-id="${name}"]`) || document.getElementById(id) || document.createElement('style'); + styleRef.current = getCurrentStyleRef(styleContainer); if (!styleRef.current.isConnected) { styleRef.current.type = 'text/css';