Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material UI: Use theme in React Class Component

I am looking for something like ThemeConsumer (which probably doesn't exist). I've React component and I am using withStyles() higher-order component to inject custom styles. It's pretty well described in documentation but I didn't find any example which uses theme.


I have some base component which contains ThemeProvider. It means any of MUI components are being affected by it.

const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
const theme = getTheme(prefersDarkMode);
return (
   <ThemeProvider theme={theme}>
      ...
   </ThemeProvider>
)

I also use some functional components with makeStyles() to create styles with provided theme.

const useStyles = makeStyles(theme => ({
   // here I can use theme provided by ThemeProvider
});

But it can't be used in class components. So I am using withStyles() HOC.

const styles = {
   // I would like to use here provided theme too
}
export default withStyles(styles)(SomeComponent);

Summary of my question:
How do I use provided theme in class component?

like image 915
Jax-p Avatar asked Mar 12 '20 16:03

Jax-p


People also ask

Can we use material UI in class component?

To customize a specific part of a component, you can use the class name provided by Material UI inside the sx prop. As an example, let's say you want to change the Slider component's thumb from a circle to a square. First, use your browser's dev tools to identify the class for the component slot you want to override.

How do I get material UI themes?

Theme provider If you wish to customize the theme, you need to use the ThemeProvider component in order to inject a theme into your application. However, this is optional; MUI components come with a default theme.


1 Answers

withStyles supports similar syntax as makeStyles:

const styles = theme => ({
   // here I can use theme provided by ThemeProvider
});
export default withStyles(styles)(SomeComponent);

Here's a simple working example:

import React from "react";
import { withStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";

const StyledPaper = withStyles(theme => ({
  root: {
    backgroundColor: theme.palette.secondary.main
  }
}))(Paper);
export default function App() {
  return (
    <StyledPaper className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </StyledPaper>
  );
}

Edit withStyles using theme

like image 65
Ryan Cogswell Avatar answered Sep 18 '22 12:09

Ryan Cogswell