Home > Net >  How to change the border color when error Helper text appears on TextField?
How to change the border color when error Helper text appears on TextField?

Time:09-22

I am using React Material UI TextField element. The thing I want is when I press submit button the helpertext which I get is "Please enter the password".

Like this:

enter image description here

But when the helpertext appears I need to change the TextField border color to the color which I want to apply from the SCSS file. As I want to change the border color through the SCSS file.

The thing I want is on focus is something like this. The TextField border should be red and its outline should be blue:

enter image description here

The code I have done so far:

<TextField
  id="form-el-2 outlined-basic"
  name="userName"
  variant="outlined"
  placeholder={"Please enter valid password"}
  helperText={
    errorMsgs.userNameErr && errorMsgs.userNameErr.length
      ? errorMsgs.userNameErr
      : null
  }
  onChange={handleChange}
  value={cabinetInfo.userName}
/>;

And also SCSS:

.MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline {
    border: 1px solid;
    border-color: #c4c4c4;
    outline: 1px solid $primary-color !important;
    outline-offset: 1px;
  }

How to do that? Is this possible? Thank you for advance.

CodePudding user response:

You can pass error prop to the <TextField />

Refer this example or Material-ui documentation here.

<TextField
  error
  id="outlined-error-helper-text"
  label="Error"
  defaultValue="Hello World"
  helperText="Incorrect entry."
/>

CodePudding user response:

You can create a custom class, then apply it to your component conditionaly

// Whatever classname or styles you want
.text-field-with-error {
    border: 1px solid;
    border-color: #c4c4c4;
    outline: 1px solid $primary-color !important;
    outline-offset: 1px;
}

and the Jsx part will be:

<TextField className={hasError ? "text-field-with-error" : " "} />
  • Related