2

In my Gatsby app I am using MUI v5, and must also output user created markup. I want the user-markup to get the same base-styles as their analogous Typography elements (see below). How can I achieve this?

Note - the user markup already contains <p> <h1> or other tags, which cannot be directly modified by React.

Additionally the app is wrapped with ThemeProvider and I'm using styled-components as the style engine for MUI (if that matters...).

import {Typography} from "@mui/material"
export default function() {
  return (
    <>
      <Typography variant="body1" paragraph>My styled Typography</Typography>
      // The next line can't receive any classses or modifiers, 
      // but must end up styled like the <Typography> element.
      <p>my custom user content - how can i style this like above?</p>
    </>
  )
}
dotist
  • 63
  • 8

3 Answers3

1

You need to import your theme. From there you can access the body1 default typography style to apply to the p element.

import {Typography} from '@mui/material'
import {useTheme} from //im not exactly sure where this comes from '@mui/material' or '@mui/styles'

export default function() {

  const theme = useTheme()

  return (
    <>
      <Typography variant="body1" paragraph>My styled Typography</Typography>
      <p style={theme.typography.body1}>my custom user content - how can i style this like above?</p>
    </>
  )
}
coot3
  • 516
  • 3
  • 7
  • The user-content already contains `

    ` `

    ` or other markup tags that i can't modify with React - at best i could add styles to their parent... Is there a way to globally make all `

    ` etc. tags inherit `theme.typography.body1` ?

    – dotist Nov 15 '21 at 06:40
  • How do you do this for other elements besides Typography, like the styles of a `Link` for instance? – Steven D. Jan 04 '22 at 02:48
1
import {useTheme ,Typography} from "@mui/material"
    
    export default function() {
    
      const theme = useTheme()
    
      return (
        <>
          <Typography variant="body1" paragraph>My styled Typography</Typography>
          <p style={theme.typography.body1}>my custom user content - how can i style this like above?</p>
        </>
      )
    }
Samira
  • 2,361
  • 1
  • 12
  • 21
1

If you want to add the sx prop in your custom component:

const P = styled("p")({});
const theme = useTheme()
<P sx={{ ...theme.typography.body1 }}>

If you want to use system properties:

import { unstable_extendSxProp as extendSxProp } from "@mui/system";

const Psx = styled("p")();

function P(inProps) {
  const { sx, ...other } = extendSxProp(inProps);
  return <Psx sx={sx} {...other} />;
}
<P {...theme.typography.body1}>

If you want to use variant prop like in Typography:

const T = styled('p')(({ theme, variant = 'body1' }) => ({
  ...theme.typography[variant],
}));
<T variant="h3">

Live Demo

Codesandbox Demo

Related Answer

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230