Search code examples
reactjstypescriptmaterial-uistyled-componentsemotion

How to convert div + useStyles to styled from @emotion/styled?


I am having trouble to convert material-ui makeStyles with theme which is applied to div into my custom div made with styled from emotion.

Following code is what am I trying to convert:

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      display: 'flex',
      flexWrap: 'wrap',
      '& > *': {
        margin: theme.spacing(2),
        width: theme.spacing(23),
        height: theme.spacing(23),
      },
      padding: '10px 10px',
    },
  }),
);

which is used in div like in this example:

<div className={classes.root}>someContent</div>

and my custom div made with styled looks like this, but the problem is that those options are not applied. (Side note: I am using the ThemeProvider from @material-ui/core/styles to supply the theme)

const CustomDiv = styled.div<{ theme: Theme }>`
  display: 'flex',
  flexWrap: 'wrap',
  '& > *': {
    margin: ${(props) => props.theme.spacing(2)},
    width: ${(props) => props.theme.spacing(23)},
    height: ${(props) => props.theme.spacing(23)},
  },
  padding: '10px 10px',
`;

Help :)


Solution

  • I figure it out (syntax used was wrong), my customDiv should be like this:

    export const StyledDiv = styled.div<{ theme: Theme }>`
      display: flex;
      flex-wrap: wrap;
      > * {
        margin: ${(props) => props.theme.spacing(2)}px;
        width: ${(props) => props.theme.spacing(23)}px;
        height: ${(props) => props.theme.spacing(23)}px;
      }
      padding: 2px 10px;
    `;