diff --git a/components/lib/hooks/useStyle.js b/components/lib/hooks/useStyle.js index dbacbfff93..96efa2657d 100644 --- a/components/lib/hooks/useStyle.js +++ b/components/lib/hooks/useStyle.js @@ -1,4 +1,5 @@ import { useEffect, useRef, useState } from 'react'; +import PrimeReact, { PrimeReactContext } from '../api/Api'; import { DomHandler, ObjectUtils } from '../utils/Utils'; let _id = 0; @@ -6,6 +7,7 @@ let _id = 0; export const useStyle = (css = {}, options = {}) => { const [isLoaded, setIsLoaded] = useState(false); + const context = React.useContext(PrimeReactContext); const cssRef = useRef(null); const defaultDocument = DomHandler.isClient() ? window.document : undefined; const { document = defaultDocument, immediate = true, manual = false, name = `primereact_style_${++_id}`, media } = options; @@ -23,6 +25,10 @@ export const useStyle = (css = {}, options = {}) => { el.type = 'text/css'; el.setAttribute('data-pc-name', name); if (media) el.media = media; + + const nonce = (context && context.nonce) || PrimeReact.nonce; + + DomHandler.addNonce(el, nonce); document.head.appendChild(el); } @@ -37,7 +43,7 @@ export const useStyle = (css = {}, options = {}) => { const node = document.querySelector(`[data-pc-name="${name}"]`); if (node && node.isConnected) { - document.head.removeChild(node); + DomHandler.removeInlineStyle(node); setIsLoaded(false); } }; diff --git a/components/lib/utils/DomHandler.js b/components/lib/utils/DomHandler.js index 64e1364bd3..13cf91034e 100644 --- a/components/lib/utils/DomHandler.js +++ b/components/lib/utils/DomHandler.js @@ -981,15 +981,7 @@ export default class DomHandler { static createInlineStyle(nonce) { let styleElement = document.createElement('style'); - try { - if (!nonce) { - nonce = process.env.REACT_APP_CSS_NONCE; - } - } catch (error) { - // NOOP - } - - nonce && styleElement.setAttribute('nonce', nonce); + DomHandler.addNonce(styleElement, nonce); document.head.appendChild(styleElement); return styleElement; @@ -1009,6 +1001,18 @@ export default class DomHandler { return styleElement; } + static addNonce(styleElement, nonce) { + try { + if (!nonce) { + nonce = process.env.REACT_APP_CSS_NONCE; + } + } catch (error) { + // NOOP + } + + nonce && styleElement.setAttribute('nonce', nonce); + } + static getTargetElement(target) { if (!target) return null;