How to use breakpoints in Theme definition itself

Viewed 386

Material-ui allows you to create a nice Theme definition object to override the default Material Design look and feel. However, when you define a Theme, it's sometimes necessary to be able to create a breakpoint based override (mobile, marginTop is 10, desktop, marginTop is 5).

Any idea on how to do that. Obviously, since the Theme is not yet defined, you don't have access to theme reference and through that theme.breakpoints

1 Answers

You can create the default theme (createMuiTheme without any arguments), and then use that theme to access the breakpoints for use in your custom theme.

Here's an example:

import React from "react";
import ReactDOM from "react-dom";
import Typography from "@material-ui/core/Typography";
import { createMuiTheme, MuiThemeProvider } from "@material-ui/core/styles";

const defaultTheme = createMuiTheme();
const theme = createMuiTheme({
  typography: {
    h4: {
      fontSize: "0.5rem",
      "&:after": {
        content: '" mobile"'
      },
      [defaultTheme.breakpoints.up("sm")]: {
        fontSize: "1.5rem",
        "&:after": {
          content: '" sm up"'
        }
      },
      [defaultTheme.breakpoints.up("md")]: {
        fontSize: "3rem",
        "&:after": {
          content: '" md up"'
        }
      }
    }
  }
});
function App() {
  return (
    <MuiThemeProvider theme={theme}>
      <div className="App">
        <Typography variant="h4">Here is some h4 text.</Typography>
      </div>
    </MuiThemeProvider>
  );
}

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

Edit breakpoints in theme creation

Related