0

Given a TextField, is there a way I can detect that it has text input, and then style the border only on that condition?

I'm using the outlined TextField. It has placeholder text when empty.

<TextField variant="outlined" />

Currently I've only succeeded in changing the text input color when it's filled by detecting if there's placeholder text currently visible.

In my overrides:

MuiOutlinedInput: {
  root: {
    '& $notchedOutline': {
      borderColor: 'green', // default colour, want to change this when field has input
    },
  },
  input: {
    '&:not(:placeholder-shown)': {
      color: 'red', // input field text becomes red when input is provided
    },
  },
},

Code Sandbox

I want the border to also become red here when the user enters text. I can't get the placeholder trick to work on changing the border color because the border by default is on the <fieldset> not the <input>. Does anyone have any ideas?

Bert
  • 55
  • 5

1 Answers1

1

Because CSS has no pseudo selector to detect whether input is empty or not (this question), so you must programmatically detect input and override the TextField border color

<TextField
  id="fullName"
  placeholder="Full name"
  variant="outlined"
  value={this.state.inputValue}
  onChange={(e) => this.setState({ inputValue: e.target.value })}
  InputProps={{
    classes: {
      notchedOutline: this.state.inputValue && classes.greenBorder
    }
  }}
/>

Codesandbox for demo

Edit material-ui textfield (forked)

hgb123
  • 13,869
  • 3
  • 20
  • 38