Unable to modify border color for Material-UI OutlinedInput

Having some trouble changing the border color of a v4.13 MaterialUI Outlined Input. No luck with CSS overrides.

Tested multiple CSS rules targeting different elements, such as select and OutlinedInput. Here are my latest attempts. What am I missing?

const styles = () =>
  createStyles({
    select: {
      "&:before": {
        borderColor: "red"
      },
      "&:after": {
        borderColor: "red"
      },
    },
    outline: {
      "&:before": {
        borderColor: "red"
      },
      "&:after": {
        borderColor: "red"
      },
    }
  });

   <Select
      label={label}
      fullWidth={true}
      error={touched && invalid}
      className={inputStyles}
      classes={{ root: classes.select }}
      input={
        <OutlinedInput
          {...input}
          fullWidth={true}
          id={input.name}
          labelWidth={this.state.labelWidth}
          classes={{notchedOutline: classes.outline}}
        />
      }
      {...custom}
   >
      {children}
    </Select>

Identified where border-color is set, but can't seem to override it.

https://i.sstatic.net/1GUWT.png

Answer №1

Below is an illustration that demonstrates how to achieve this using version 4 (v5 example provided later):

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import OutlinedInput from "@material-ui/core/OutlinedInput";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";

const useStyles = makeStyles(theme => ({
  root: {
    display: "flex",
    flexWrap: "wrap"
  },
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120
  },
  selectEmpty: {
    marginTop: theme.spacing(2)
  }
}));
const useOutlinedInputStyles = makeStyles(theme => ({
  root: {
    "& $notchedOutline": {
      borderColor: "red"
    },
    "&:hover $notchedOutline": {
      borderColor: "blue"
    },
    "&$focused $notchedOutline": {
      borderColor: "green"
    }
  },
  focused: {},
  notchedOutline: {}
}));

export default function SimpleSelect() {
  const classes = useStyles();
  const outlinedInputClasses = useOutlinedInputStyles();
  const [values, setValues] = React.useState({
    age: "",
  });

  const inputLabel = React.useRef(null);
  const [labelWidth, setLabelWidth] = React.useState(0);
  React.useEffect(() => {
    setLabelWidth(inputLabel.current.offsetWidth);
  }, []);

  function handleChange(event) {
    setValues(oldValues => ({
      ...oldValues,
      [event.target.name]: event.target.value
    }));
  }

  return (
    <form className={classes.root} autoComplete="off">
      <FormControl variant="outlined" className={classes.formControl}>
        <InputLabel ref={inputLabel} htmlFor="outlined-age-simple">
          Age
        </InputLabel>
        <Select
          value={values.age}
          onChange={handleChange}
          input={
            <OutlinedInput
              labelWidth={labelWidth}
              name="age"
              id="outlined-age-simple"
              classes={outlinedInputClasses}
            />
          }
        >
          <MenuItem value="">
            <em>None</em>
          </MenuItem>
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>
    </form>
  );
}

https://codesandbox.io/s/outlinedinput-border-color-u1br7?fontsize=14

To delve deeper into this topic, consider exploring the following related responses:

  • Customize outline for OutlinedInput in React Material-UI
  • Extensive global outlined customization
  • Altering border color on Material-UI TextField components

Here's a closely related scenario tailored for v5 of Material-UI utilizing styled:

import React from "react";
import { styled } from "@material-ui/core/styles";
import { outlinedInputClasses } from "@material-ui/core/OutlinedInput";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";

const StyledForm = styled("form")(`
  display: flex;
  flex-wrap: wrap;
`);
const StyledFormControl = styled(FormControl)(({ theme }) => ({
  margin: theme.spacing(1),
  minWidth: 120
}));
const StyledSelect = styled(Select)(`
  & .${outlinedInputClasses.notchedOutline} {
    border-color: red;
  }
  &:hover .${outlinedInputClasses.notchedOutline} {
    border-color: blue;
  }
  &.${outlinedInputClasses.focused} .${outlinedInputClasses.notchedOutline} {
    border-color: lime;
  }
`);

export default function SimpleSelect() {
  const [values, setValues] = React.useState({
    age: ""
  });

  function handleChange(event) {
    setValues((oldValues) => ({
      ...oldValues,
      [event.target.name]: event.target.value
    }));
  }

  return (
    <StyledForm autoComplete="off">
      <StyledFormControl variant="outlined">
        <InputLabel id="outlined-age-simple-label">Age</InputLabel>
        <StyledSelect
          labelId="outlined-age-simple-label"
          value={values.age}
          onChange={handleChange}
          name="age"
          label="Age"
        >
          <MenuItem value="">
            <em>None</em>
          </MenuItem>
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </StyledSelect>
      </StyledFormControl>
    </StyledForm>
  );
}

https://codesandbox.io/s/outlinedinput-border-color-29715?fontsize=14&hidenavigation=1&theme=dark

Answer №2

In accordance with the accurate response from Ryan Cogswell, this can also be achieved in Mui 5 by utilizing sx props.

<OutlinedInput
    name="age"
    onChange={handleChange}
    sx={{
        "& .MuiOutlinedInput-notchedOutline" : {
            borderColor : "red",
         },
        "&:hover > .MuiOutlinedInput-notchedOutline" : {
            borderColor : "lime"
         }
       }}
/>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Identify the browser dimensions and implement CSS styling for all screen resolutions

I am currently facing an issue with a function that I have created to apply CSS changes to a menu based on browser resizing and different resolutions. The problem lies in the fact that my function does not seem to be correctly interpreted by the browser. W ...

Retrieving results from PostgreSQL database using pagination technique

When I'm pagination querying my data from a PostgreSQL database, each request involves fetching the data in this manner: let lastNArticles: Article[] = await Article.findAll({ limit: +req.body.count * +req.body.page, or ...

Facing Hurdles in Starting my Debut Titanium Mobile Project

I recently started using Titanium Studio (version 2.1.0GA on WindowsXP) and I have added the Android SDK to it. However, I am encountering an error when trying to run my first mobile project. The console is displaying the following message: Can anyone off ...

Update the function to be contained in a distinct JavaScript file - incorporating AJAX, HTML, and MySQL

Currently, I am working on a project and need to showcase a table from MySQL on an HTML page. The JavaScript function in my code is responsible for this task, but due to the Framework 7 requirement, I must separate the function into a different .js file ra ...

Regular expression that prohibits the acceptance of numbers with leading zeros

Below is the directive I am using to ensure that the input consists purely of numbers from 0-9. import { Directive, HostListener, ElementRef } from "@angular/core"; @Directive({ selector: "[numbersOnly]", }) export class OnlynumberDi ...

Creating Flutter UI designs that seamlessly adapt to all screen sizes without the need for scrolling

Just a quick question as I embark on creating my very first Flutter App. Currently, I am working on the Login Screen, which features a simple design with a welcoming text and two rows for Google and Apple sign-in options. I want to avoid making the page s ...

Experiencing challenges with socket io connectivity between my backend and Quasar application. Encountering a 403 Forbidden error while trying to establish a connection with

I recently updated my Quasar app and ran into issues with the websocket connection after switching from development to production mode. The app is hosted on an Express server via pm2 on my Ubuntu server, which also connects to a database. Here are some sn ...

Tips for implementing a personalized color scheme with Material UI

Currently, I am attempting to incorporate my own theme into my React Js app with the help of Material UI. If someone could guide me through the process step by step, it would be greatly appreciated. I have limited experience in both ReactJs and Material ...

Enhance Vaadin 14: Automatically adjust TextArea size when window is resized

Using Vaadin 14.1.19 in a project called "My Starter Project," I attempted to create a TextArea that supports multiple lines. Initially, everything seemed fine, but upon resizing the TextArea, it failed to adjust the number of visible lines. Here is the co ...

Using JavaScript: Retrieve the URL from a JSON file and run it in the background

I am looking to make a JSON request using jQuery: $.getJSON('http://example.com/file.php', function(data) { //data }); An example of the JSON output: { "url":"http://example.com/execute.php" } Next, I want to silently execute the URL on th ...

How can checkboxes be combined from two separate tables?

Within this interactive code example, you will find two tables containing checkboxes in each row. Upon clicking the To button, a dialog box will appear allowing you to select users or groups from a drop-down menu. The corresponding tables will then be dis ...

Clicking again on the second onclick attribute

I have an image file named image1.png. When the button is clicked for the first time, I want it to change to image2.png. Then, when the button is clicked for a second time, I want it to change to yet another image, image3.png. So far, I've successful ...

Dealing with redirecting to the login page in Angular

I recently started working with Angular and I feel completely lost. My initial task involves making a simple Rest-GET request, but the destination is located behind an external login page. This results in my request being redirected to the external page a ...

What causes the button size to change in Bootstrap when switching to a spinner?

Every time I switch from a spinner back to a button, the button's size changes. I am struggling to identify the cause of this issue. function resizeButton() { var btn = document.getElementById('submitBtn'); btn.innerHTML = ' ...

Simultaneously executing React and Node

I have encountered a challenge with my use case that involves integrating React into my existing express/EJS application. Currently, the express app is running on port 35, while I am trying to add React by following a tutorial and running it on a different ...

What is the best way to use form input to filter an Observable?

Within my component, I have declared the variable "countries$": countries$!: Observable<Country[]>; To populate this variable with data from this API, I use the following code in the "ngOnInit" lifecycle hook: ngOnInit(){ this.countries$ ...

While `getServerSideProps` functions properly in development mode, it encounters failures in production. However, the `useSWR

In my Next.js project, I encountered an issue where my data fetching code works perfectly in development mode but throws a "request failed with error 503" error when deployed to production using Vercel. Interestingly, client-side fetching with useSWR works ...

Drag and drop surprise: When items are dragged onto the screen, a magical box will appear. But watch as the box disappears when the item is dragged

I am a newcomer to knockout JavaScript and am currently utilizing Knockout drag and drop functionality in my project. Initially, I have two divisions - one is visible while the other has a display property set to none. During the drag enter function, I wan ...

Error in React application: The object does not have support for the property or method 'closest'

Attempting to launch my React app (built with Material-UI) on IE 11 has been a challenge. Certain functionalities are not working properly, and I am encountering the following error in my browser: https://i.sstatic.net/MKvxl.png I have experimented with d ...

Excessive Empty Area beneath <td>

I'm currently working on creating an e-book and I have encountered a concerning issue. The <figure> and <figcaption> elements are appearing as unknown tags in Sigil. To work around this problem, I decided to use a <table> for display ...