Search code examples
reactjsreact-reduxmaterial-designmaterial-ui

how to change the asterisk color in required * field


I have two required fields in my form .I want the asterisk color should be red.Currently it is showing black .I am using material UI react library ? here is my code https://codesandbox.io/s/r7lq1jnjl4 documents https://material-ui.com/demos/text-fields/

<FormControl>
                  <TextField
                    required
                    InputLabelProps={{
                      shrink: true
                    }}
                    id="standard-name"
                    label="Name"
                    margin="normal"
                    helperText="Some important text"
                  />
                </FormControl>

Solution

  • Based on this documentation on how to customize components through theme overrides for a FormLabel (which will also include InputLabel), you should use createMuiTheme and add the following overrides:

    const formLabelsTheme = createMuiTheme({
      overrides: {
        MuiFormLabel: {
          asterisk: {
            color: '#db3131',
            '&$error': {
              color: '#db3131'
            },
          }
        }
      }
    })
    

    Then, you wrap your <form> within a <MuiThemeProvider> like so:

    <MuiThemeProvider theme={formLabelsTheme}>
      <form noValidate autoComplete="off">
    
    ...
    ...
    ...
    
      </form>
    </MuiThemeProvider>
    

    Here is a forked code sandbox which demonstrates this code in action.

    Since you are already creating a theme, you could just put your overrides in that theme, but you'll need to move your <form> to be within the <MuiThemeProvider> that you already have in your code.

    The resulting form labels look like this: resulting form, with theme overridden