1

I'd like to create a reusable component using Material-UI's api (not using styled-components.) I got this far - and it almost works - but the settings that use theme variable don't work (e.g, bgcolor and padding). Am I doing something wrong - or is this not possible?

  const BigPanel = styled(Box)({
    display: 'flex',
    width: '100%',
    flexgrow: 1,
    bgcolor: 'background.paper',
    borderRadius: 10,
    boxShadow:'1',
    p:{ xs: 4, md: 8 }
  });
Ryan Cogswell
  • 75,046
  • 9
  • 218
  • 198
Bob Glass
  • 465
  • 3
  • 12

1 Answers1

1

The object passed to styled is intended to be CSS properties, but you have a mixture of CSS properties and Box props (bgcolor, p). Even the ones that are valid CSS properties (display, width) are also valid Box props, so the most straightforward solution is to specify all of them as props.

One way to handle this is to use defaultProps. This makes it very easy to override some of the props when using the component by specifying them explicitly as shown in the example below.

import React from "react";
import Box from "@material-ui/core/Box";
import CssBaseline from "@material-ui/core/CssBaseline";
import { styled } from "@material-ui/core/styles";

const BigPanel = styled(Box)({});
BigPanel.defaultProps = {
  display: "flex",
  width: "100%",
  borderRadius: 10,
  flexGrow: 1,
  bgcolor: "background.paper",
  p: { xs: 4, md: 8 },
  boxShadow: "1"
};
export default function App() {
  return (
    <>
      <CssBaseline />
      <BigPanel>Default BigPanel</BigPanel>
      <BigPanel bgcolor="primary.main" color="primary.contrastText">
        BigPanel with explicit props
      </BigPanel>
    </>
  );
}

Edit styled Box

In the example above, styled isn't really serving any purpose anymore except to create a new component type. Though it isn't less code, below is an alternative way to get the same effect without using styled:

const BigPanel = React.forwardRef(function BigPanel(props, ref) {
  return <Box ref={ref} {...props} />;
});
BigPanel.defaultProps = {
  display: "flex",
  width: "100%",
  borderRadius: 10,
  flexGrow: 1,
  bgcolor: "background.paper",
  p: { xs: 4, md: 8 },
  boxShadow: "1"
};

Edit styled Box (forked)

Ryan Cogswell
  • 75,046
  • 9
  • 218
  • 198