How can I properly use Material UI breakpoints with styled components?

Viewed 112

I have:

const FooterBox = styled(Box)`
  background: #4e738a;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  color: #ffffff;


  ${p => p?.theme?.breakpoints.up('xs')} {
     margin: auto;
     display: flex;
     flex-direction: column;
     align-items: center;
     justify-content: space-between;
   }

   ${p => p?.theme?.breakpoints.up('md')} {
    margin: auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
  }
`;

But TypeScript is complaining: Property 'breakpoints' does not exist on type 'Theme'.ts(2339)

1 Answers

You got this error because you are using styled from the @emotion package, to avoid this use styled from the @mui package.

This also fixes other issues with the MUI theme in Typescript:

  • Property 'shapes' does not exist on type 'Theme'.ts(2339)
  • Property 'breakpoints' does not exist on type 'Theme'.ts(2339)
  • Property 'transitions' does not exist on type 'Theme'.ts(2339)
  • Property 'palette' does not exist on type 'Theme'.ts(2339)
  • ...
// import styled from '@emotion/styled';
import { styled } from "@mui/material/styles";
import Box from "@mui/material/Box";

const FooterBox = styled(Box)(({ theme }) => ({
  background: "#4e738a",
  left: 0,
  right: 0,
  bottom: 0,
  width: "100%",
  color: "#ffffff",

  [theme.breakpoints.up("xs")]: {
    margin: "auto",
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "space-between"
  },

  [theme.breakpoints.up("md")]: {
    margin: "auto",
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "space-between"
  }
}));

export default function App() {
  return (
    <div className="App">
      <FooterBox>Hello Wolrd!</FooterBox>
    </div>
  );
}

Edit dazziling-code

Related