Search code examples
reactjsmaterial-uimaterial-designtextfieldreact-jsonschema-forms

How can I us a theme to style all material-ui inputs as if they had a variant='outlined'?


I use theming to control the overall styling of my app, and a large number of TextField components throughout.

I'd like them all to appear by default as having variant='outlined' (because despite MUI's explanations for it, the greyed out box is poor UX - it looks too much like a disabled text field).

Using my own OutlinedTextField component (where I override the default variant and pass all other props to TextField isn't an option, since I use tools such as rjsf-material-ui.

It seems we can set variants (I see it noted here in their theming docs but can't find an example, and can't wrap my head around whether I have to do it by overriding a variant, or by altering a global css rule.

How do I edit a theme to use `variant='outlined' on all TextFields?


Solution

  • OK, solved it myself.

    1. Find the name of the component to override, in the css section of the component API page... https://material-ui.com/api/text-field/#css. In my case the component name is MuiTextField.

    2. You can apply default props in the theme itself (I was confused because I thought I had to override the css... not the case).

    For MUI v4

    const appThemeOptions = {
      ...baseThemeOptions,
      overrides: {
        // DON'T do it using css overrides like this one...
        MuiPaper: {
          rounded: {
            borderRadius: '0px',
          },
        },
      },
      // DO use the props directly
      props: {
        MuiTextField: {
          variant: 'outlined',
        },
      },
    }
    const appTheme = createMuiTheme(appThemeOptions)
    

    For MUI v5 and v6

    There is a slightly different API for MUI v5 where you override defaultProps not props (thanks to @Titenis for their comment)...

    createTheme({
      components: {
        MuiTextField: {
          defaultProps: {
            variant: 'outlined',
          },
        },
      },
    })