How to mount styles inside shadow root using cssinjs/jss

前端 未结 2 1727
别跟我提以往
别跟我提以往 2020-12-18 08:38

I\'m trying to use https://material-ui.com/ components inside shadow dom, and need a way to inject those styles inside shadow dom. by default material-ui, which

2条回答
  •  遥遥无期
    2020-12-18 09:14

    Using https://github.com/Wildhoney/ReactShadow to create shadow dom (you could also do it by hand as shown in previous answer), I created a small WrapperComponent that encapsulates the logic.

    import root from 'react-shadow';
    import {jssPreset, StylesProvider} from "@material-ui/styles";
    import {create} from 'jss';
    import React, {useState} from "react"
    
    const WrappedJssComponent = ({children}) => {
      const [jss, setJss] = useState(null);
      
      function setRefAndCreateJss(headRef) {
        if (headRef && !jss) {
          const createdJssWithRef = create({...jssPreset(), insertionPoint: headRef})
          setJss(createdJssWithRef)
        }
      }
      
      return (
        
          
            
          
          {jss &&
          
            {children}
          
          }
        
        
      )
    }
    
    export default WrappedJssComponent
    

    Then you just need to Wrap your app, or the part of your app you want to shadow inside .

    Be careful, some of the material-UI component won't work as usual (I had some trouble with

    • ClickAwayListener, maybe because it uses the parent dom, did not investigate more than that to be honest.
    • Popper, and everything that will try to use document.body as container will not have access to jss defined in shadow node. You should give an element inside the shadow dom as container.

提交回复
热议问题