Home > front end >  How to override border-color in outlined styled TextField component in Material-UI
How to override border-color in outlined styled TextField component in Material-UI

Time:12-31

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 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?

CodePudding user response:

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
      }
    }
  }
});

CodePudding user response:

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.

  • Related