Apply MUI styles to non-MUI markup elements

Viewed 400

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>
    </>
  )
}
3 Answers

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>
    </>
  )
}
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>
        </>
      )
    }

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

Related