Home > database >  How to set the default style of MaterialUI TextField as if it were in focus?
How to set the default style of MaterialUI TextField as if it were in focus?

Time:11-01

I am learning Material UI ( ver.5.10.10 ) for the first time. I want to customize the TextField of material UI. As I do not like the transition from focus off to focus on I would like the TextField styling to always show as if it were in focus (I don't want it to be in focus, just the same style as if it were).

I'm searching in documentation & google in general but I have no clue how I can achiev this.

Images explaining:

MUI TextField

(1) This is the default style of the TextField, without focus

MUI TextField Focused

(2) This is the default style of the TextField when in focus

I would like it to always look like in (2) , no matter if it's in focus or not

I tried to find a property that allows changing this behavior but I didn't find anything, I guess it could be done with a customTheme? Or maybe there is a simpler way

Thanks!

CodePudding user response:

Please check below code for your requirement. You can always check the API page of the component. on API page bottomside there are CSS selectors. you can use them to customize the css of the compoent.

e.g.

1)https://mui.com/material-ui/api/text-field/#css 2) https://mui.com/material-ui/api/outlined-input/#css

<TextField
    label="Outlined"
    variant="outlined"
    InputLabelProps={{ shrink: true }}
    sx={{
      "& .MuiOutlinedInput-root": {
        "& fieldset": {
          borderColor: "primary.main",
          borderWidth: "2px"
        }
      },
      "& .MuiFormLabel-root": {
        color: "primary.main"
      },
    }}
  />

CodePudding user response:

You should try using onFocus and onBlur react's events on the input itself.

function Input() {
  return (
    <input 
      id="someId"
      type="text"
      name="inputName"
      onFocus={(e) => handleOnFocusEvent(e)} 
      onBlur={(e) => handleOnBlurEvent(e)}
      placeholder="Outlined"
      style={{
         position: "relative",
         zIndex: 1,
      }}
    />
  )
}

for example if you have an input element like the above, you can try to modify the placeholder style on onFocus event and then resetting the style when the onBlur event occurs (onBlur event occurs when the element is not in focus). You can access the placeholder styles like this:

"&::placeholder": {
  position: "absolute",
  top: 0,
}

if your input has position: relative; zIndex: 1; try on onFocus event to set the placeholder styles to position: absolute, top: 0, left: 0, you can try using GSAP library to make a cool animation or just set a transition css property on the input itself.

  • Related