Custom MUI FormControlLabel Examples: Font Size, Width, Error

The Material UI FormControlLabel is composed of a FormControl, a Label, and whatever control component is passed in (checkbox, switch, radio). This means we have to explore the DOM to find classes to use as selectors and make sure we target the correct child element.

Here’s what we will create in this tutorial:

MUI FormControlLabel Example
MUI FormControlLabel Example

This post is part of a series on Checkboxes and Switches wrapped in FormControlLabels.

Material UI FormControlLabel Font Size and Width

The first thing we need to do is understand how the FormControlLabel renders. In the screenshot below, I highlighted the label element in the DOM.

MUI FormControlLabel DOM
MUI FormControlLabel DOM

Notice that it is a sibling of the checkbox and a child of the label with class MuiFormControlLabel-root. We can use this information for our selectors.

I used the sx prop to add styling. This will be applied at the root component, which is the label with class MuiFormControlLabel-root. To target the actual label element that renders text we need a nested selector.

In the code below I used a space after the & to create a nested selector targeting a child element with class MuiFormControlLabel-label. I then added font size, width, and background color (to show the width more clearly).

const formControlLabelStyle = {
  "& .MuiFormControlLabel-label": {
    fontSize: "1.5rem",
    width: 300,
    backgroundColor: 'rgba(0,0,0,0.1)'
  }
}

//JSX
<FormControlLabel 
  control={
    <Checkbox 
      name="badData"
      checked={badData}
      onChange={handleChange}
    />
  }
  label="Bad Data"
  sx={{...formControlLabelStyle}}
/>

Material UI FormControlLabel Error

I added the error prop to the parent FormControl component (see code here). I expected some default styling to apply to the FormControlLabel text, but no visual change happened.

However, at the root of the FormControlLabel, I noticed that class Mui-error was applied. I then used this class in a selector, and styled the proper child label with the default theme error color.

const formControlLabelStyle = {
  "&.Mui-error .MuiFormControlLabel-label": {
    color: 'error.main'
  }
}

Some components inherit parent FormControl error states immediately, but usually child components wrapped with their own FormControl (like TextField) don’t see error states from FormControls higher up in the DOM.

Resources

Related Posts:

MUI FormControlLabel API Docs

Share this post:

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.