Ivone Djaja
Ivone Djaja

Reputation: 763

Customize asterisk color of the label in the required TextField on variant default, focused, and filled

I am able to change the color of asterisk by createTheme in the default state.

export const theme = createTheme({
  MuiFormLabel: {
    styleOverrides: {
      asterisk: {
        color: '#E54D39',
      },
    },
  },
});

TextField - default variant

TextField default variant

But the asterisk color should be blue like the label and not red when the TextField is focused or filled. But I don't know how to customize in createTheme because Mui-focused is not inside the same element as MuiFormLabel-asterisk.

TextField - focused variant

TextField focused variant

TextField focused in dev tools

MuiFormLabel: {
  styleOverrides: {
    // This is not working
    // root: {
    //  '&.MuiFormLabel-focused': {
    //    asterisk: {
    //      color: '#E54D39',
    //    },
    //  },
    // },
    asterisk: {
      color: '#E54D39',
    },
  },
},

Upvotes: 1

Views: 228

Answers (1)

Steve G
Steve G

Reputation: 13442

From the MUI docs Overrides based on props:

You can pass a callback as a value in each slot of the component's styleOverrides to apply styles based on props.

The ownerState prop is a combination of public props that you pass to the component + internal state of the component.

As a part of ownersState for MuiFormLabel, you can get the focused and filled states which will give you what you're looking for. For example:

const theme = createTheme({
  components: {
    MuiFormLabel: {
      styleOverrides: {
        asterisk: ({ ownerState }) => ({
          color: ownerState.focused || ownerState.filled ? "inherit" : "#E54D39"
        })
      }
    }
  }
});

Which produces:

example fields

Working CodeSandbox: https://codesandbox.io/s/textfield-asterisk-with-ownerstate-js-7wghtl?file=/src/Demo.js:186-428

Upvotes: 1

Related Questions