Derick Schoonbee
Derick Schoonbee

Reputation: 3021

Nested styling within Typography

How can I style my text with <Typography /> ? Is it possible to do something like this:

const someText = 'Hello <b>World</b>';

...
  <Typography>
   {someText}
  </Typography>
...

Or do I need to split up my text? With nested Typographies I seem to have some layout issues.

Upvotes: 7

Views: 9830

Answers (5)

Debanjan Tewary
Debanjan Tewary

Reputation: 129

I think this will be the easiest one.

import {styled} from "@mui/material";

const Span = styled("span")();

<Typography variant="body1">
  Hello <Span sx={{...}}>World</Span>
</Typography>

Upvotes: 0

Philip Sopher
Philip Sopher

Reputation: 783

Use a basic html within the Typography

<Typography>
  Hello <b>World</b>
</Typography>

or

<Typography>
  Hello <span style={{ font-weight: 'bold' }}>World</span>
</Typography>

Upvotes: 0

Ali Elkhateeb
Ali Elkhateeb

Reputation: 3733

You can use Box Component

It accepts the properties fontWeight and display like this:

<Typography component="div">
    This is normal text <Box display="inline" fontWeight="fontWeightBold">this is bold</Box>
</Typography>

NOTE: Make sure you add component="div" to your Typography otherwise you'll get the following error:

<div> cannot appear as a descendant of <p>

Here is a codesandbox

Upvotes: 3

Siraj Alam
Siraj Alam

Reputation: 10055

I'm using material-ui 4.* and doing this is perfectly legal.

<Typography variant={'h5'} >Treffen Sie auf der it-sa 2019 die Micro Focus 
     <Typography display={'inline'} >und diskutieren Sie über </Typography>
</Typography>

Upvotes: 9

Derick Schoonbee
Derick Schoonbee

Reputation: 3021

I finally made use of a custom style like this:

const styleSheet = createStyleSheet('SomeComponent', (theme) => ({
  root: {
  },
...
  body2Bold: {
    fontFamily: theme.typography.body2.fontFamily,
    fontSize: theme.typography.body2.fontSize,
    fontWeight: 'bold',
  },
}));

And then in my render function:

const { Hello, World, classes } = this.props;
...
    <Typography type="body2" color="default">
        {Hello}
        <span className={classes.body2Bold}>
          &nbsp;{World}
        </span>.
    </Typography>
...

The down side is that I need to break up some text into different variables.

Upvotes: 4

Related Questions