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?
However, this is optional; MUI components come with a default theme. ThemeProvider relies on the context feature of React to pass the theme down to the components, so you need to make sure that ThemeProvider is a parent of the components you are trying to customize. You can learn more about this in the API section.
The majority of styles that are applied to Material-UI components are part of the theme styles. In some cases, you need the ability to style individual components without changing the theme. For example, a button in one feature might need a specific style applied to it that shouldn’t change every other button in the app.
There are many other styling options available to your Material-UI app beyond withStyles (). There’s the styled () higher-order component function that emulates styled components. You can also jump outside the Material-UI style system and use inline CSS styles or import CSS modules and apply those styles.
First, you need to install the Material UI framework into your React application. This will install the core components of the framework along with the tools to manage the theme. Next, you’ll need to define a global theme for your application.
OK, solved it myself.
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
.
You can apply default props in the theme itself (I was confused because I thought I had to override the css... not the case).
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)
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',
},
},
},
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With