Material-UI Core TextField globally set InputLabelProps shrink

Viewed 18950

Does anyone know how to globally override the shrinking of the label with a Material-UI Textfield (or Input if I need to use this)?

I dont want to add this everywhere:

...      
InputLabelProps={{
    shrink: true,
}}

but I cant seem to figure out the correct override in createMuiTheme.

I have tried adding shrink: true here

overrides: {
    MuiInput: { ...

and here

overrides: {
    MuiInputLabel: { ...

But I cant get it working.

If someone could point my to the docs/code to where they figured this out too, that would be awesome!

Thanks

3 Answers

Just to clarify, in version 1 (and later) theme overrides allow you to customize a component's styles, not props. This is approach is a lot more powerful as it gives you full control over all Material UI Styles.

In this case, you would need to modify the styles for each TextField variant so the shrink styles are applied by default (see implementation)

The best solution is to create a custom variation of the component, as Alireza suggested. Here is an example:

import TextField from "@material-ui/core/TextField";

function CustomTextField({ InputLabelProps = {}, ...props }) {
  return (
    <TextField
      InputLabelProps={{ ...InputLabelProps, shrink: true }}
      {...props}
    />
  );
}

Edit Material UI - Custom TextField

if you want to override some method of the basic component, in my opinion, the best way is to create custom component and change whatever you need then use your own component inside your project . for this react gives you anything you want

If you really don't want to bother with creating a custom component, you can use theme overrides to get it close. Simply copy the shrink css properties to the MuiInputLabel. Something like this:

MuiInputLabel: {
  outlined: {
    transform: 'translate(14px, -6px) scale(0.75)',
    transformOrigin: 'top left',
    padding: '0 2px',
    background: '#ffffff',
  },
},

It's not perfect, as the padding is applied to both the shrink and override, but it's very close.

Also, if you aren't using 'outlined', you don't need the padding or background properties and it should look identical to the other fields with 'shrink'.

Related