Issue with React MUI V5 causing theme not to display properly within shadow-root element

After trying to attach the shadow root using the MUI createTheme function, I encountered rendering issues. Despite following the instructions in this helpful guide on the MUI website, my problem persists.

// App.js
const cache = createCache({
  key: 'css',
  prepend: true,
  container: shadowRoot,
  speedy: false
})

return (
  <StyledEngineProvider injectFirst>
    <CacheProvider value={cache}>
      <ThemeProvider theme={themes(customization)}>
        <CssBaseline />
        <NavigationScroll>
          <Routes />
        </NavigationScroll>
      </ThemeProvider>
    </CacheProvider>
  </StyledEngineProvider>
);
// themes.js
const themeOptions = {
  direction: 'ltr',
  palette: themePalette(themeOption),
  mixins: {
    toolbar: {
      minHeight: '48px',
      padding: '16px',
      '@media (min-width: 600px)': {
        minHeight: '48px'
      }
    }
  },
  typography: themeTypography(themeOption)
};

const themes = createTheme(themeOptions);
themes.components = componentStyleOverrides(themeOption);

return themes;
// componentStyleOverrides
const shadowRoot = flowise.shadowRoot.querySelectorAll('#mountPoint')[0];

MuiCssBaseline: {
  defaultProps: {
    container: shadowRoot
  },
  styleOverrides: {
    body: {
      scrollbarWidth: 'thin',
      scrollbarColor: theme?.customization?.isDarkMode
        ? `${theme.colors?.grey500} ${theme.colors?.darkPrimaryMain}`
           .
           .
           .

Despite attempting to mount it in the shadow root, the solution still doesn't seem to be effective:

Answer №1

It seems like the issue you're encountering could be related to how you're applying Material-UI styles to a component inside a Shadow DOM. To successfully integrate Material-UI with Shadow DOM, it's essential to ensure that the styles are encapsulated correctly within the Shadow DOM. This might require some tweaking.

Follow these steps for using Material-UI with Shadow DOM:

Start by importing the necessary libraries: import { createTheme, CssBaseline, StyledEngineProvider, ThemeProvider } from '@mui/material'; import { CacheProvider } from '@emotion/react'; import createCache from '@emotion/cache';

Create a cache and attach it to the Shadow DOM:

const shadowRoot = document.querySelector('#your-shadow-root-selector');                 
// Replace this with your specific selector
const cache = createCache({
  key: 'css',
  prepend: true,
  container: shadowRoot,
  speedy: false,
});

Define your theme and incorporate the cache:

const theme = createTheme({
  // Your theme configuration goes here
});
theme.components = componentStyleOverrides(theme);

return (
  <StyledEngineProvider injectFirst>
    <CacheProvider value={cache}>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        {/* Insert your app content here */}
      </ThemeProvider>
    </CacheProvider>
  </StyledEngineProvider>
);

Ensure that your componentStyleOverrides function assigns the correct container property for MuiCssBaseline. Here's an example:

const componentStyleOverrides = (themeOption) => {
  const shadowRoot = document.querySelector('#your-shadow-root-selector'); // Replace with your actual selector

  return {
    MuiCssBaseline: {
      defaultProps: {
        container: shadowRoot,
      },
      styleOverrides: {
        // Add your styles here
      },
    },
    // Other component overrides
  };
};

Remember to replace #your-shadow-root-selector with the appropriate selector for your Shadow DOM. The container property should target the root element of your Shadow DOM.

By implementing these adjustments, Material-UI styles should seamlessly integrate within the Shadow DOM of your component. Be sure to use accurate selectors and IDs tailored to your specific scenario.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are some ways to utilize symbol fonts such as marvosym within a web browser?

Are you looking to use special LaTeX fonts like \Pluto from marvosym in your web development projects? Wondering how to display this symbol with HTML / JavaScript / CSS without relying on an image? You can download the font from This symbol corresp ...

Navigating the Terrain of Mapping and Filtering in Reactjs

carModel: [ {_id : A, title : 2012}, {_id : B, title : 2014} ], car: [{ color :'red', carModel : B //mongoose.Schema.ObjectId }, { color ...

The functionality of the Cordova camera plugin is not functioning properly within a React JS component

Currently, I am in the process of developing a PhoneGap hybrid application with react js and react-router. The app utilizes the cordova camera plugin and is being tested on an iPhone using the PhoneGap developer app. However, there seems to be an issue a ...

Creating a dynamic dropdown menu: a step-by-step guide

<ul class="nav navbar-nav friend-label"> <li class="dropdown" ng-repeat="module in modules"> <a href="" class="dropdown-toggle" data-toggle="dropdown"> {{module.ModuleName}} < ...

Setting a static width for a specific cell in HTML5 - What's the best way to go about it?

When working with HTML5, how do I define a specific width for a table cell? Many of the <col> properties that were present in HTML4 are no longer applicable in HTML5. Just to clarify, I am aware that I can use <td style="width:150px">, but thi ...

Having trouble troubleshooting errors related to uploading files in NextJS? The upload feature was functioning perfectly until the update to version 14, but now it seems to be causing

Encountering errors with the uploadthing and NextJS integration. The upload feature was functional until version 14, but now facing issues. Reverted back to NextJS version 13 only to encounter console errors (Windows VSCode Terminal). PS C:\Users&bsol ...

How can I trigger a pop-up window in React for my specific scenario?

​ Looking to enhance my skills in React, I have a question for you - how can I trigger a popup window from the following code snippet: ​ import {options, columns,convertToArray} from './consts' ​ const index = () => { ​ co ...

Navigating through the complexities of managing asynchronous props and state in React-components

I'm really struggling to understand this concept. My current challenge involves passing asynchronously fetched data as props. The issue is that the props themselves are also asynchronous. Below is a simplified version of the component in question: i ...

The element is inferred to have an 'any' type due to the fact that a 'string' type expression cannot be used to access elements in the type '{ Categories: Element; Admin: Element; }'

As someone who is new to TypeScript, I am trying to understand why I am encountering a type error in the code below (simplified): "use client"; import { ArrowDownWideNarrow, Settings } from "lucide-react"; interface LinkItemProps { ...

Nav bar taking up full width of page, centered to the right with content area

I am facing an issue with aligning my full-width navbar with my fixed content area. The ul keeps changing based on the browser or resolution. Check out this fiddle for reference: http://jsfiddle.net/fwyNy/ subject site CSS Code: #topribbon{ width: 10 ...

Jumbotron causes navigation bar to malfunction on mobile site

I'm experiencing an issue with Bootstrap Jumbotrons on my website - they extend beyond the container, causing the navbar on the mobile version to not fill the screen. This problem only occurs on pages with a jumbotron present. Attempting to use a Car ...

In ReactJS, one can create a variable and include a map function by first declaring the variable and then using the map function within the component. If you

Having trouble integrating the accordian.js page into the app.js main page for compilation. Need help defining and writing out the function correctly, any suggestions? Below is my code: App.js: How do I incorporate the components from the accordian.js pa ...

Steps for organizing a list based on the number of clicks

I've created an HTML list with images of political party logos. Each logo is a grid item that can be clicked on. I want to sort the list based on the number of clicks each logo receives, essentially ranking them by popularity. However, I'm not su ...

Why isn't the length of the Array changing when using React's useState hook

I am facing a challenge trying to understand why the value of inputElementArray.length consistently remains 0 when accessed within the useEffect method. function view() { const [inputElementArray, setInputElementArray] = useState<HTMLInputElement[]& ...

Axios transforms into a vow

The console.log outputs of the api and axios variables in the provided code are showing different results, with the state axios becoming a Promise even though no changes were made. The 'api' variable holds the normal axios instance while 'ax ...

First render does not define useEffect

Why am I experiencing an issue here? Whenever I attempt to retrieve data from my API, it initially returns undefined during the first render, but subsequent renders work correctly. const [data, setData] = useState([]) useEffect(() => { const fe ...

Is there a way to customize the visual appearance of radio buttons by using unique color schemes

Incorporating bootstrap 4, I have implemented a basic set of custom yes/no radio buttons. <div class="custom-control custom-radio custom-control-inline"> <input type="radio" id="rd_1" name="rd" class="custom-control-input green" value="Yes"&g ...

Unable to adjust the size of a DIV with a button click in Vue3

I am having trouble resizing a DIV block in Vue3. Whenever I click the button, I receive an error message saying "Cannot read properties of undefined (reading 'style')". I know there is an issue with the JS part of the code, but I'm not sure ...

Dropzone user interface package experiencing issues with displaying image previews

I recently installed the dropzone-ui package and noticed that while file items load and file icon previews show up when I drop files on the dropzone, image previews are not displaying. Could it be an issue with my implementation? Here's a snippet of ...

The content of my menu is concealed within a DIV. It may remain hidden or malfunction

I am in the process of creating master pages. In one of the master pages, I have implemented a dropdown menu using jQuery and CSS. While it works perfectly fine on some pages, it seems to be hidden on others that contain a div element. This is because the ...