Why is my css module not overriding material ui styles?

Viewed 669

I am using nextJs and css modules and attempting to override the material ui classes

 <Toolbar classes={{ root: cn(styles.root) }} />

I have the Styles Provider and injectFirst attribute as specified in the material docs.

 <StylesProvider injectFirst>
    <Head />
    <HttpInterceptor />
      <CssBaseline />
      <Layout pageProps={pageProps}>
        <Component {...pageProps} />
      </Layout>
  </StylesProvider>

And the material css is being injected first... enter image description here

But the material root class is still overriding my root class...

What am I missing here?

enter image description here

1 Answers

Figured it out. I had previously copied this _document.tsx configuration from the material nextjs example.

`import Document, { Head, Html, Main, NextScript } from 'next/document'
 import React from 'react'

 import { ServerStyleSheets } from '@material-ui/core/styles'

 export default class MyDocument extends Document {
   render() {
   return (
   <Html lang="en">
    <Head />
    <body>
      <Main />
      <NextScript />
    </body>
   </Html>
   )
   }
   } 

  // `getInitialProps` belongs to `_document` (instead of `_app`),
  // it's compatible with server-side generation (SSG).
 MyDocument.getInitialProps = async ctx => {


 // Resolution order
  //
  // On the server:
  // 1. app.getInitialProps
  // 2. page.getInitialProps
  // 3. document.getInitialProps
  // 4. app.render
  // 5. page.render
  // 6. document.render
  //
  // On the server with error:
  // 1. document.getInitialProps
  // 2. app.render
  // 3. page.render
  // 4. document.render
  //
  // On the client
  // 1. app.getInitialProps
  // 2. page.getInitialProps
  // 3. app.render
  // 4. page.render

  // Render app and page and get the context of the page with collected side effects.
  const sheets = new ServerStyleSheets()
  const originalRenderPage = ctx.renderPage

  ctx.renderPage = () =>
    originalRenderPage({
      enhanceApp: App => props => sheets.collect(<App {...props} />)
    })

  const initialProps = await Document.getInitialProps(ctx)

  return {
    ...initialProps,
    // Styles fragment is rendered after the app and page rendering finish.
    styles: [
      sheets.getStyleElement(),
      ...React.Children.toArray(initialProps.styles)
    ]
  }
}

And that was injecting the material ui code again after my style sheets.

enter image description here

And this hook removes the server side styles after it's loaded.

  React.useEffect(() => {
// Remove the server-side injected CSS.
const jssStyles = document.querySelector('#jss-server-side')
if (jssStyles) {
  jssStyles.parentElement.removeChild(jssStyles)
}
}, [])

If anyone has a deeper explanation of what's going on here, I would love to hear it

Related