Styles from head (data-primereact-*) are not inserted into shadow dom
Describe the bug
If I enclose my primereact app inside a shadow dom, the styles that normally show up on head are not inserted into the shadow dom instead.
Reproducer
No response
PrimeReact version
10.0.9
React version
18.x
Language
TypeScript
Build / Runtime
Angular 16
Browser(s)
No response
Steps to reproduce the behavior
Mount a react app with primereact inside an angular component with shadow dom encapsulation.
Verify that the primereact layer styles only show up in head, not in the shadow dom they are mounted in.
Expected behavior
No response
Please fork the CodeSandbox project or Stackblitz project and create a case demonstrating your bug report. This issue will be closed if no activities in 20 days.
It appears that the relevant code is here
https://github.com/primefaces/primereact/blob/b0e41bdd6cb58a028252066c2eb69c89015a73f9/components/lib/hooks/useStyle.js#L30
and that I am able to solve the problem with this
function createStyle(node: HTMLElement, styleContent: string) {
if (!styleContent) { debugger; return; }
const e = document.createElement("style");
e.textContent = styleContent;
if (!node.parentNode) { debugger; return; }
node.parentNode.appendChild(e);
}
export function ReactView<P extends {}>({ injector, Comp, props, node }: { injector: Injector; Comp: React.FunctionComponent<P>; props: P; node: HTMLElement; }) {
useEffect(() => {
if (!node) return;
const base = document.querySelector("[data-primereact-style-id='base']")?.textContent ?? "";
const global = document.querySelector("[data-primereact-style-id='global']")?.textContent ?? "";
const common = document.querySelector("[data-primereact-style-id='common']")?.textContent ?? "";
// const r = node.current.getRootNode();
createStyle(node, base);
createStyle(node, global);
createStyle(node, common);
}, [node])
return (
<MyProviders>
<Comp {...props} />
</MyProviders>
)
}
/* ... elsewhere in an angular component ... */
@Input() component: any;
@ViewChild("approotslot")
set approotslot(v: ElementRef) {
// ... check if we're already mounted on this element ...
// ... unmount existing roots first ...
// mount the root on the element we just recieved
this.root = createRoot(this._approotslot);
this.root.render(createElement(ReactView, {
node: v.nativeElement,
injector: this.injector,
Comp: this.component,
props: {},
}));
}
root?: Root;
Do you have a PR to propose?
Do you have a PR to propose?
I don't know enough about PrimeReact to understand why it doesn't play well with the shadow DOM, so not really. That being said, here's where I'm at now. Basically I just create an angular component and append it to the location, then add everything to the shadow DOM. It's a hacky solution but it allows me to still use angular to manage the SCSS.
@Component({
providers: [FormsQuestionService],
selector: 'react-app-prime',
template: ``,
styles: [`
@import "../../../../../react-prime/themes/material/material-light/compact/indigo/theme.scss";
`],
encapsulation: ViewEncapsulation.ShadowDom
})
export class ReactAppPrimeComponent {
}
export function ReactShadowBoundary({ className, children, component, doPrime }: PropsWithChildren<{ component: any, className: string, doPrime?: boolean }>) {
const placeholderRef = useRef<HTMLDivElement | null>(null);
const [curComp, setComp] = useState<ComponentRef<any> | null>(null);
const { injector, get } = useAngular();
useLayoutEffect(() => {
if (!placeholderRef.current) return;
const view = get(ViewContainerRef);
const comp = view.createComponent(component, { injector });
placeholderRef.current.appendChild(comp.location.nativeElement);
setComp(comp);
}, [placeholderRef.current]);
useLayoutEffect(() => {
if (!doPrime) { debugger; return; }
const node = curComp?.location.nativeElement.shadowRoot;
if (!node) return;
const base = document.querySelector("[data-primereact-style-id='base']")?.textContent ?? "";
const global = document.querySelector("[data-primereact-style-id='global']")?.textContent ?? "";
const common = document.querySelector("[data-primereact-style-id='common']")?.textContent ?? "";
createStyle(node, base);
createStyle(node, global);
createStyle(node, common);
function createStyle(node: ShadowRoot, styleContent: string) {
if (!styleContent) { return; }
const e = document.createElement("style");
e.textContent = styleContent;
node.appendChild(e);
}
}, [curComp?.location.nativeElement.shadowRoot, doPrime]);
return <div style={{display: "contents"}} className={className} ref={placeholderRef}>{
curComp?.location.nativeElement.shadowRoot ? createPortal(children, curComp.location.nativeElement.shadowRoot) : null
}</div>;
}
@Arlen22
Maybe I am wrong and do not understand your problem correctly but...
I do not think it is the responsibility of Primereact or React to get styles into the Shadow DOM. I think the builder should do that
What I do for Vite or Webpack:
Vite: I use this vite plugin package: vite-plugin-shadow-dom-css See: https://stackblitz.com/edit/vitejs-vite-nuemax?file=src%2Fmain.jsx
And for Webpack in webpack.config.js: (do not have a stackblizt of this)
module: {
...,
rules: [
...,
{
test: /\.(css|scss)$/i,
use: [
{
loader: "style-loader",
options: {
injectType: 'styleTag',
insert: function insertIntoShadowDom(element) {
var parent = document.getElementById('root').shadowRoot;
var lastInsertedElement = window._lastElementInsertedByStyleLoader;
if (!lastInsertedElement) {
parent.insertBefore(element, parent.firstChild);
} else if (lastInsertedElement.nextSibling) {
parent.insertBefore(element, lastInsertedElement.nextSibling);
} else {
parent.appendChild(element);
}
// eslint-disable-next-line no-underscore-dangle
window._lastElementInsertedByStyleLoader = element;
}
}
},
"css-loader",
"sass-loader",
],
},
],
Hope this helps
Ok, how add dynamical css from
? This css contains style prime for TabView etc.