reactjsmaterial-uicustom-elementreact-typescript

mui Select drop down options not styled when using entry point to insert scoped shadow DOM styles


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):

enter image description here

Dropdown options are showing like this:

enter image description here


Solution

  • You should add MenuProps.disablePortal = true to mount Menu inside shadow DOM (to be able to use scoped styles)

    <Select MenuProps={{ disablePortal: true }}>