'Gatsby Mui Theme is undefined when generating pages

I am using Mui and Gatsby. I have created the theme in a layout.js like so:

const Layout = ({ children, location, pageTitle, crumbs }) => {
  const data = useStaticQuery(graphql`
    query SiteTitleQuery {
      site {
        siteMetadata {
          title
        }
      }
    }
  `)


  return (
    <>
      <ThemeProvider theme={theme}>
        <Header siteTitle={data.site.siteMetadata?.title || `Title`} />
        <CssBaseline />

        <Main >
          
            <CustomBreadcrumbs
              crumbLabel={pageTitle}
              location={location}
              crumbs={crumbs}
            />
         
          {children}</Main>
        <footer
          style={{
            marginTop: `2rem`,
          }}
        >
          © {new Date().getFullYear()}, Built with
          {` `}
          <a href="https://www.gatsbyjs.com">Gatsby</a>
        </footer>

      </ThemeProvider>
    </>
  )
}

I have a page component, that has some styles, and are trying to pass theme to page template but when I check the props from the page template Component, theme is undefined and I can also not use it in the styles object I have created.

Page template is like this:

class ProductDetail extends React.Component {

  render() {
    
    console.log(this.props)
    const product = get(this.props.data, 'contentfulProduct')
    const { classes } = this.props
    const {
      breadcrumb: { crumbs },
    } = this.props.pageContext
    let images = []
    if (product.packagePhoto) {
      images.push(product?.packagePhoto)
    }
    if (product.kibblePhoto) {
      images.push(product?.kibblePhoto)
    }
    if (product.productPhoto) {
      images.push(product?.productPhoto)
    }
    if (product.ambPhoto) {
      images.push(product?.ambPhoto)
    }

    return (
      <Layout location={this.props.location} pageTitle={`${product.brand.brandName} ${product.name}`} crumbs={crumbs}>
       ....some code here

      </Layout>
    )

  }

}

export default withStyles(styles, { withTheme: true })(ProductDetail)

I can not use theme in styles object in page template:

const styles = theme => ({
  root: {
    width: '100%'
  },
  paragraph: {
    marginBottom: '20px'
  },
  halfWidthParagraph:{
    marginBottom: '20px',
    width: '50%',
   /*  [theme.breakpoints.down('sm')]:{
      width: '100%'
    } */
  }

})

How can I load the "theme" into the Page Component and use it in the styles object?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source