Reputation: 833
Note that this is for MUI v5 @mui/material and NOT using v4 @material-ui/core
After finally figuring out how to make @mui/material styles show when using an entry point to emotion to insert scoped shadow DOM styles (see this post How to create insertion point to mount styles in shadow dom for MUI material v5 in React custom element), it turns out the Select drop down is not getting styled correctly for the Demo component which contains the @mui/material components.
Here is the stackblitz https://stackblitz.com/edit/react-d8xtdu-s2cufr?file=demo.js
import React from 'react';
import Demo from './demo';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import { StylesProvider, jssPreset } from '@mui/styles';
import { CacheProvider } from '@emotion/react';
import createCache from '@emotion/cache';
import { create } from 'jss';
import { render } from 'react-dom';
const theme = createTheme();
class MyWebComponent extends HTMLElement {
connectedCallback() {
const shadowRoot = this.attachShadow({ mode: 'open' });
const emotionRoot = document.createElement('style');
const mountPoint = document.createElement('div');
shadowRoot.appendChild(emotionRoot);
const reactRoot = shadowRoot.appendChild(mountPoint);
const jss = create({
...jssPreset(),
insertionPoint: reactRoot,
});
const cache = createCache({
key: 'css',
prepend: true,
container: emotionRoot,
});
render(
<StylesProvider jss={jss}>
<CacheProvider value={cache}>
<ThemeProvider theme={theme}>
<Demo />
</ThemeProvider>
</CacheProvider>
</StylesProvider>,
mountPoint
);
}
}
if (!customElements.get('my-element')) {
customElements.define('my-element', MyWebComponent);
}
Instead of showing like this (in addition click events are not getting captured correctly, particularly cannot click on select box arrow to close it):
Dropdown options are showing like this:
Upvotes: 2
Views: 2498
Reputation: 1
We can use MenuProps.disablePortal = true
to force the menu to be displayed inside the shadow DOM. However, this setting prevents the select menu from displaying correctly in modals, as the modals may overlap the menu, causing it to be cut off. In MUI v6, there is a container
property that allows us to specify the root element where the Select Menu should be mounted.
const getMyShadowDomRoot = () => {
const shadowRoot = document.querySelector('#app')?.shadowRoot.
if (shadowRoot) {
return shadowRoot.querySelector('#myShadowRootApp');
}
return document.body;
}
<Select MenuProps={{ container: getMyShadowDomRoot() }}>
Here the link to the MUI documentation: https://mui.com/material-ui/api/popover/#popover-prop-container
Upvotes: 0
Reputation: 1610
You should add MenuProps.disablePortal = true
to mount Menu inside shadow DOM (to be able to use scoped styles)
<Select MenuProps={{ disablePortal: true }}>
Upvotes: 6