Search code examples
javascriptreactjstypescriptmaterial-uistyled-components

Material UI & Styled Component Overriding Issue


I was using Material UI's Typography and it worked perfectly:

 <Typography component="h1" variant="h5">
          Sign in
        </Typography>

However, I wanted to move to styled-components so I tried using this:

export const Typo = styled(Typography)`
    component: h1;
    variant: h5;
`;

Although the properties are exactly the same, this Typography came out different and smaller. How can I fix it? What am I doing wrong? Do I need to use something else except componentand variant?

I also tried this but it didn't make a difference.

export const Typo = styled(Typography)`
  && {
    component: h1;
    variant: h5;
  }
`;

Solution

  • You only write CSS inside the styled body:

    styled(Typography)`
      /* Only CSS here */
    `
    

    what you're doing is writing props in here which will not work. You can pass those props to your styled component and it will work just fine.

    export const Typo = styled(Typography)`
        /* Write your CSS here */
    `;
    
    // Pass your props to Typo
    <Typo component="h1" variant="h5" />
    

    If you want to bind props with the Styled component and not worry about them when rendering the component, you can do it with attrs() method:

    export const Typo = styled(Typography).attrs({
      component: 'h5',
      variant: 'h1'
    })`
        /* Write your CSS here */
    `;
    
    // No need to pass props anymore, they are bind to this component
    <Typo />