Unable to apply custom border color to Material UI Select component in React

I have been experimenting with material-ui v5 to improve my skills. I am currently struggling to customize the default style of the mui Select component. My goal is to modify the color of the Select element when it is being hovered over or in a focused state. The current appearance of the focused state is shown below.

https://i.sstatic.net/Rn4k0.png

Below is the snippet of my code:

import { useState, useEffect } from 'react';
import { makeStyles } from '@mui/styles';
import { Select, MenuItem } from '@mui/material';

const useStyles = makeStyles({
    select: {
     '&.MuiOutlinedInput-root': {
       width: '200px'
     },
    '& .MuiOutlinedInput-notchedOutline': {
        borderColor: 'red',
          '&:hover': {
          borderColor: 'green'
        }
     },

    }
})

function App() {
  const classes = useStyles();
  const [age, setAge] = useState('');

  const handleChange = (event: SelectChangeEvent) => {
    setAge(event.target.value);
  };
  return (
        <Select
          variant="outlined"
          className={classes.select}
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={age}
          label="Age"
          onChange={handleChange}
        >
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
  );
}

export default App;

Any form of assistance would be highly appreciated.

Answer №1

First and foremost:

@mui/styles is the traditional styling solution for MUI. It relies on JSS for styling, which is no longer used in @mui/material, as it has been deprecated in v5. If you prefer not to have both emotion and JSS in your bundle, it is recommended to consult the @mui/system documentation for an alternative.

You can find more information here. For customization, it is advised to use styled-components.

Select components in MUI utilize input fields behind them, and in order to achieve your desired customization, you will need to modify the input using the .MuiOutlinedInput-root class. MUI provides some examples of input customizations here.

Below is a custom example of a Select:

const CustomSelect = styled(Select)(() => ({
  width: 300,
  "&.MuiOutlinedInput-root": {
    "& fieldset": {
      borderColor: "red"
    },
    "&:hover fieldset": {
      borderColor: "yellow"
    },
    "&.Mui-focused fieldset": {
      borderColor: "green"
    }
  }
}));

Answer №2

By utilizing the latest API for styling, known as "styled", you can easily customize your components by leveraging the class objects provided by the MUI library. It is crucial to note that no spaces should be left between the '&' and the '.' in the CSS, or else it may not function as intended. Give it a try! In this example, I am adjusting the border color of a Select component on hover using the :hover selector and in the focused state with the focused class from the component. The select is specified as notchedOutlined, hence the corresponding class is applied.

 import {
  Select,
  outlinedInputClasses,
  selectClasses
} from '@mui/material';
import { styled } from '@mui/system';

export const StyledSelect = styled(Select)`
  width: 150px;
  height: 40px;
  color: #fff;
  border-color: #fff;

  & .${selectClasses.icon} {
    color: #fff;
  }

  & .${outlinedInputClasses.notchedOutline} {
    border-color: #fff;
  }
  &:hover .${outlinedInputClasses.notchedOutline} {
    border-color: #fff;
  }

  &.${outlinedInputClasses.focused} .${outlinedInputClasses.notchedOutline} 
  {
    // IMPORTANT NOTE: NO SPACES BETWEEN '&' AND '.'
    border-color: #fff !important;
  }
`;

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

Removing an Element in a List Using Jquery

In my JQuery, there is a list named additionalInfo which gets populated using the function below: $('#append').on('click', function () { //validate the area first before proceeding to add information var text = $('#new-email&a ...

Extracting specific keys from JSON data

I am working with an array named cols: var cols = ["ticker", "highPrice", "lowPrice","lastPrice"] // dynamic The JSON data is coming from the backend as: info = {ticker: "AAPL", marketCap: 2800000000, lowPrice: 42.72, highPrice: 42.84} If I want to sel ...

Difficulty in converting class-based JS useState array to TypeScript Hook

Recently, I've delved into the world of React / TypeScript and have taken on a personal project to enhance my skills. As part of this project, I am in the process of transitioning some class-based code into hooks. Here is the (JS) class-based code th ...

What is the best way to extract information from a JSON XHR request and incorporate it into my template?

I am brand new to using Ember. Right now, my main goal is to connect to an API that provides random text and then show that text on a webpage. The specific API endpoint I am using is "" which will give back a response in JSON format. app/controllers/rando ...

Objects that are included into an array will end up with an undefined value

Currently, I am in the process of coding a command for my Discord bot that involves adding items to an array of objects stored within a JSON file. To achieve this functionality, I have implemented the following code snippet: let rawdata = fs.readFileSync(& ...

How can we best understand the concept of custom directives using the link method?

As a beginner in AngularJS, I am looking to implement an autocomplete feature for text input. My JSON data is stored in JavaScript and I need help simplifying the process. Can you provide me with a straightforward solution? The specific requirement is to ...

Ways to conceal and reveal content within div elements

I have a code snippet that is currently operational, but I am looking to enhance it by displaying one div at a time. If you would like to view the code, please visit my CodePen link below: https://codepen.io/danongu/pen/YzXvpoJ Due to the extensive amou ...

Printing Apex Oracle reports using Internet Explorer

I am facing a challenge with printing my page that contains two interactive reports. To enable printing, I have utilized a JavaScript function that triggers window.print(). I have incorporated CSS to adjust the layout of my tables when printed. @media pr ...

Encountering the error "Text content does not match" when using Next.js with next-i18next

I have followed the instructions for setting up next-i18next, but I am encountering an error that says "Text content did not match. Server: Testing ZH HANT Client: Testing EN" - even though only English text is displayed on the frontend. I seem to have ove ...

How to choose multiple images in Ionic framework

I am working with the following HTML structure: <div ng-repeat="image in images"> <img ng-src="img/{{image}}_off.png" /> </div> Additionally, I have the following JavaScript code in the controller: $scope.images = ['imga',&ap ...

Using a border-radius on Internet Explorer 11 reveals the background through the corners

Encountering issues with rounded borders in IE 11 (11.0.9600.18350)? Check out this minimal fiddle for more information: https://jsfiddle.net/7phqrack/2/ Here's the HTML code snippet: <div class="backgrounddiv"> <div class="outer"> ...

React component fails to update upon data changes

Is there a way for React to detect changes in the database value for 'count' and update the view automatically? Do I need to create a function in the component that is called by the DB to manually update the state or prop, or is there a method wh ...

How can I center align my loader inside app-root in Angular2+?

I've successfully added a basic spinner to my <app-root> in the index.html file. This gives the appearance that something is happening behind the scenes while waiting for my app to fully load, rather than showing a blank white page. However, I& ...

Two interconnected queries with the second query relying on the results of the first

I am currently facing a challenge in my Phonegap (Cordova) application where I need to display a list of items, each requiring an additional query. Let me simplify it with an example scenario. Imagine a student can be enrolled in multiple courses and a co ...

Ensure that both the top row and leftmost column are fixed in a vertical header using JQuery DataTable

Check out the implementation of vertical header flow in Datatables by visiting: https://jsfiddle.net/2unr54zc/ While I have successfully fixed the columns on horizontal scroll, I'm facing difficulty in fixing the first two rows when vertically scroll ...

Dynamically fetching data with Node.js using Ajax requests

Despite my efforts to scour Google and Stack Overflow, I have been unable to find a reliable method for posting data to my Node.js server. I've noticed conflicting information on various methods, likely due to changes over time. One particular code ...

Tips on how to dynamically load the content of a URL into a modal and update the browser address simultaneously

I am attempting to achieve a specific effect using JavaScript and jQuery Link to the content I want to load in a modal The goal is to load the content in a modal while keeping the main page in the background. Additionally, when a URL is followed, I want ...

Using Bootstrap 4: How to maximize the width of a span element placed near a label

I need to adjust the width of a span next to its label in my project. My goal is to show multiple groups {label / data} on the same line. To achieve this, I divided the row into 4 columns and tried to set a specific width for a span. However, no matter wh ...

Achieve seamless transitions between animations when hovering with CSS3

I am facing an issue with an element that has a CSS3 animation. When the element is hovered over, the animation changes to another infinite one. While everything is functioning correctly, the transition between animations sometimes feels too abrupt and b ...

The binding element 'params' is assumed to have a type of 'any' by default

I encountered an issue The binding element 'params' implicitly has an 'any' type. Below is the code snippet in question: export default function Page({ params }) { const { slug } = params; return ( <> <h1>{s ...