Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
876 views
in Technique[技术] by (71.8m points)

reactjs - Add custom theme variable object to createMuiTheme()

By default the material UI theme is a combination of several pre-defined objects such as typography: {...}, palette: {...} etc.

Is is possible to add a custom object into this setup and still use createMuiTheme?

So for example the theme object would become:

const theme = {
  palette: {
    primary: '#000'
  },
  typography: {
    body1: {
      fontFamily: 'Comic Sans'
    }
  },
  custom: {
    myOwnComponent: {
      margin: '10px 10px'
    }
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, this works just fine. Material-UI does a deep merge of its defaults with the object you provide with some special handling for keys that get merged in a more sophisticated fashion (such as palette, typography and a few others). Any unrecognized keys will come through unchanged.

Below is a working example:

import React from "react";
import ReactDOM from "react-dom";

import {
  useTheme,
  createMuiTheme,
  MuiThemeProvider
} from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";
const theme = createMuiTheme({
  palette: {
    primary: {
      main: "#00F"
    }
  },
  typography: {
    body1: {
      fontFamily: "Comic Sans"
    }
  },
  custom: {
    myOwnComponent: {
      margin: "10px 10px",
      backgroundColor: "lightgreen"
    }
  }
});
const MyOwnComponent = () => {
  const theme = useTheme();
  return (
    <div style={theme.custom.myOwnComponent}>
      Here is my own component using a custom portion of the theme.
    </div>
  );
};
function App() {
  return (
    <MuiThemeProvider theme={theme}>
      <div className="App">
        <Button variant="contained" color="primary">
          <Typography variant="body1">
            Button using main theme color and font-family
          </Typography>
        </Button>
        <MyOwnComponent />
      </div>
    </MuiThemeProvider>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Edit custom properties in theme


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...