Hey there,
You know that Material-UI Typography component has variant props that include 15 default types such as: h1 ~ h6
, subtitle1
, body1
, and so on. you can see options here https://material-ui.com/api/typography/
now, if you want to add some more to your Typography component and have more design for it you must create a custom typography component like below.
this is MyTypography.tsx
that is in my components directory.
import { TypographyProps, Typography } from '@material-ui/core'
import classNames from 'classnames'
import React, { ElementType, FC } from 'react'
import useMyTypographyStyle from './MyTypography.styles'
interface IMyTypography extends Omit<TypographyProps, 'variant'> {
variant:
| TypographyProps['variant']
| 'h2Bold'
| 'subtitle1Bold'
component?: ElementType
}
const MyTypography: FC<IMyTypography> = (props) => {
const classes = useMyTypographyStyle()
const isCustom = Object.keys(classes).indexOf(props.variant) > -1
return (
<Typography
{...props}
variant={isCustom ? undefined : (props.variant as any)}
className={
isCustom
? classNames(classes[props.variant], props.className)
: props.className
}
>
{props.children}
</Typography>
)
}
export default MyTypography
In this case we made a component that it variant get undefined or default Material-UI Typography variant based on isCustom
value and this value is the props when we pass to MyTypography
component.
Also you must have a style file for add your design to your custom variants.
import { makeMyStyles } from 'theme'
const useMyTypographyStyle = makeMyStyles(
({ typography }) => ({
h2Bold: { ...typography.h2, fontWeight: 700 },
subtitle1Bold: { ...typography.subtitle1, fontWeight: 700 },
}),
{ name: 'myTypography' },
)
export default useMyTypographyStyle
Thats it. we done it. now you have 17 values for your variant props and when you want to use Typography component you must use it like this
<MyTypography variant='h2Bold'>heading 2 with custom styles</MyTypography>
<MyTypography variant='subtitle1Bold'>subtutle 1 with custom styles</MyTypography>
Top comments (0)