How to use Typography as a styled component in react of material UI

Viewed 5917

I am new to the material UI. Here , I am trying to create a styled component which will be a Typography. So, what I tried is ,

import styled from 'styled-components';


 import {
  FormGroup,
  FormControlLabel,
  Tooltip,
  FormControl,
  Select,
  Radio,
  Typography,
  Button
} from '@material-ui/core'
const StyledTypography = styled.Typography<Itest>(({ marginLeft, marginRight }) => ({
}))

But this gives me a compile time error.

Property 'Typography' does not exist on type 'ThemedStyledInterface<ThemeInterface>'

Can any one help me with this ?

I have used the folowing way

const StyledTypography = styled(Typography)<ISortBySelector>(({ fontSize }) => ({
  && {
  fontFamily: 'Roboto',
  fontSize: fontSize ? fontSize : '10px',
  fontWeight: 'normal',
  fontStretch: 'normal',
  fontStyle: 'normal',
  lineHeight: 'normal',
  letterSpacing: fontSize ? '0.14px' : '0.07px',
  width: fontSize ? '50px' : '35px',
  height: fontSize ? '19px' : '14px',
  color: '#000000',
  cursor: 'pointer'
  }
}))
2 Answers

I'm not sure if you are using the right syntax there, but this is how i usually pass components into styled-components (notice I am not using dot notation). In addition, you can use the usual CSS syntax, rather than the lower camelcased format.

import Typography from '@material-ui/core/Typography';
import styled from 'styled-components';

const StyledTypography = styled(Typography)<Itest>`
   && {
     font-family: Roboto;
     // customise your styles here
   }
`;

And if you wish to pass other props into StyledTypography, for instance, setting variant as caption,

<StyledTypography variant='caption'>
  Some text
</StyledTypography>

I don't think using dot notation is your issue. I think this is what you're trying to achieve:

import { styled } from '@mui/material/styles'
import Typography from '@mui/material/Typography'

export const StyledTypography = styled(Typography)(({ theme }) => ({
  '&': {
    color: theme.palette.common.black,
    // ...and so on
  },
})) as typeof Typography

The other answer is ok if you're not using variables from your theme. Also, note that there's currently a bug with the component prop on specific components, so as typeof Typography might be needed.

Related