akds
akds

Reputation: 681

How to override border-color in outlined styled TextField component in Material-UI

The task is to use Material UI outlined input field (TextField component from "@material-ui/core": "^4.12.2",) and style it with custom blue colour.

Here's what I managed to achieve: Desired input field in active state

Current theme override for InputLabel:

import { createTheme } from "@material-ui/core/styles";

export const muiTheme = createTheme({
  overrides: {
    MuiInputLabel: {
      outlined: {
        "&$focused": {
          color: "#3f3fa0",
        },
      },
    },
  },
},

The above general theme override helps change the label ("Email address") colour to blue. The blue border-color is achieved by wrapping TextField in a styled component with the below CSS:

import styled from "styled-components";
import { TextField } from "@material-ui/core";

export const CustomTextField = styled(TextField)`
  .MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline {
    border-color: #3f3fa0;
  }
`;

I render the above component like this (inside of ThemeProvider):

<CustomTextField
  variant="outlined"
  label={label}
/>

This hacky solution works, as seen on the image I supplied above, however, sometimes Mui code decides to append random numbers to their class names and this causes my custom (hacky) CSS solution to fail and it ends up looking like this:

TextField with random CSS classess

I tried to add almost any combination I could think of to the Mui overrides object to override the border-color property but could not figure it out. Can you help?

Upvotes: 3

Views: 4541

Answers (2)

Doppio
Doppio

Reputation: 2188

Here's how to override border-color on OutlinedInput (material-ui v4).

I made a codesandbox here

const defaultColor = "#ff0000";
const hoverColor = "#0000ff";
const focusColor = "#00ff00";

const theme = createTheme({
  overrides: {
    MuiOutlinedInput: {
      root: {
        // Hover state
        "&:hover $notchedOutline": {
          borderColor: hoverColor
        },
        // Focused state
        "&$focused $notchedOutline": {
          borderColor: focusColor
        }
      },
      // Default State
      notchedOutline: {
        borderColor: defaultColor
      }
    }
  }
});

Upvotes: 4

Chuck
Chuck

Reputation: 804

Well, I am not that experienced with material-ui but this seems to be something you are looking for. https://mui.com/styles/api/#examples

Using that, I think it is possible to customize classname.

Upvotes: 0

Related Questions