Customizing Material UI Select for background and focus colors

I am looking to customize the appearance of the select component by changing the background color to "grey", as well as adjusting the label and border colors from blue to a different color when clicking on the select box. Can anyone assist me with this?

Below is the error I encountered: TS2322: Type '{ root: string; }' is not assignable to type 'Partial<SelectClasses>'.
Object literal may only specify known properties, and 'root' does not exist in type 'Partial<SelectClasses>'.

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

     import * as React from 'react';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import Select, { SelectChangeEvent } from '@mui/material/Select';
import makeStyles from '@mui/styles/makeStyles';


const useStyles = makeStyles((theme) => ({
    selectRoot: {
        '&:focus':{
            backgroundColor:'yellow'
        }
    }
}));

    export interface SelectProps {
        label: string;
        value:string | undefined;
        options:any;
        error?: boolean;
        onChange?: (value: string) => void;

    }

    export class FormDDown extends React.Component<SelectProps, {

        value: string;
    }> {


        constructor(props: SelectProps) {
            super(props);

            this.state = {value: ''};
        }

        private handleChange = (event: SelectChangeEvent) => {
            this.setState({value: event.target.value});

            // notify the callback if present
            this.props.onChange?.(event.target.value);
        }

        classes = useStyles();

        render() {
            let id = this.props.value ?? this.props.label;
            let errorBorder = { borderBottom: '2px solid red' };
        return(
            <div className='forminput'>
                <FormControl variant="filled" fullWidth>
                <InputLabel id="demo-simple-select-helper-label">{this.props.label}</InputLabel>
                <Select
                    variant="filled"
                    labelId="demo-simple-select-helper-label"
                    id="demo-simple-select-helper"
                    value={this.props.value}
                    autoWidth
                    onChange={this.handleChange}
                    style={{...(this.props.error ? errorBorder : {})}}
                    classes={{ root: this.classes.selectRoot }}
                >
                    {this.props.options.map((option:any) => {
                        return (
                            <MenuItem key={option.value} value={option.label}>
                                {option.label ?? option.value}
                            </MenuItem>
                        );
                    })}
                </Select>
            </FormControl>
        </div>
        )
}
}


Answer №1

The issue you're encountering stems from using useStyles() in a class component, which is not allowed! The useStyles() hook is specifically designed for functional components. Instead, consider utilizing the Higher-Order Component API. Here's an example that aligns with what you're looking for:

import * as React from "react";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select, {
  SelectChangeEvent,
} from "@mui/material/Select";
import { WithStyles, withStyles } from "@mui/styles";

const styles = {
  root: {
    color: "white !important",
    background: "red !important",
    border: "1px solid yellow !important"
  }
};

export interface SelectProps {
  label: string;
  value: string | undefined;
  options: any;
  error?: boolean;
  className: string | undefined;
  onChange?: (value: string) => void;
}

class FormDDown extends React.Component<
  SelectProps,
  {
    value: string;
  }
> {
  constructor(props: SelectProps) {
    super(props);

    this.state = { value: "" };
  }

  private handleChange = (event: SelectChangeEvent) => {
    this.setState({ value: event.target.value });

    // notify the callback if present
    this.props.onChange?.(event.target.value);
  };

  // this.classes = useStyles();

  render() {
    let id = this.props.value ?? this.props.label;
    let errorBorder = { borderBottom: "2px solid red" };
    return (
      <div className="forminput">
        <FormControl variant="filled" fullWidth>
          <InputLabel id="demo-simple-select-helper-label">
            {this.props.label}
          </InputLabel>
          <Select
            variant="filled"
            labelId="demo-simple-select-helper-label"
            id="demo-simple-select-helper"
            value={this.props.value}
            autoWidth
            onChange={this.handleChange}
            style={{ ...(this.props.error ? errorBorder : {}) }}
            className={this.props.className}
          >
            {this.props.options.map((option: any) => {
              return (
                <MenuItem key={option.value} value={option.label}>
                  {option.label ?? option.value}
                </MenuItem>
              );
            })}
          </Select>
        </FormControl>
      </div>
    );
  }
}

function FormDDownComponent(props: WithStyles<typeof styles>) {
  const { classes } = props;
  return (
    <FormDDown
      options={[
        { value: "single", label: "Single" },
        { value: "married", label: "Married" }
      ]}
      label="Family"
      value="0"
      className={classes.root}
    />
  );
}

export default withStyles(styles)(FormDDownComponent);

https://codesandbox.io/s/xenodochial-fast-r786u?fontsize=14&hidenavigation=1&theme=dark

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

How to employ Math.random with multiple variables in JavaScript

Within a function, I have the following statement: Math.random() > 0.5 ? 'spikes' : 'slime' I am interested in adding one more variable, let's call it 'stone', and having the program randomly choose between those th ...

What is the best way to inject a service instance into the implementation of an abstract method?

In my Angular application, I have a service that extends an abstract class and implements an abstract method. @Injectable({ providedIn: 'root', }) export class ClassB extends ClassA { constructor( private service : ExampleService) { s ...

Angular 2 - Issue: Parameters provided do not correspond to any signature of call target

I'm encountering the following error message: "error TS2346: Supplied parameters do not match any signature of call target." This occurs when attempting to reject a promise, but I believe the code adheres to the required signatures. Any suggestions on ...

Error encountered in azure devops preventing successful execution: "npm ERR! code ELIFECYCLE"

I am facing an issue with my Azure DevOps build pipeline that contains 2 npm tasks: - one for npm install - and the other for npm run-script build Unfortunately, I am encountering errors that do not provide sufficient information about the root cause of ...

Instantly summing up two numbers with javascript

In my web development work using Visual Studio 2008, I encountered an interesting challenge. On a webpage, I have three textboxes labeled "Price," "Quantity," and "Amount." The task at hand is to calculate the value of "Amount" by multiplying the values ...

Applying CSS rules from an array to elements by looping through

I'm looking for a way to allow users to input CSS styles and have those styles applied to the last selected element, which is determined by the "rangeselector" variable. Currently, the code selects the correct element, but only the first CSS rule is b ...

How can you adjust Material UI's Table Pagination to start with a non-zero index instead of the default zero-based index

When using Material UI Table pagination, the indexing starts at zero. So, even when you are on what is labeled as 'page 1', it actually resets to 'page 0'. Is there a way to make sure it stops at 'page 1'? https://i.stack.img ...

Dynamic Element with Mousewheel Event

Simply put, I am attempting to attach a 'mousewheel' event to a div that contains a scrollbar. My code functions properly when used outside of the plugin I developed, but as soon as I convert it into a plugin, it stops working. I tested changing ...

Using Regular Expressions to eliminate any characters that are not directly adjacent to numbers (beside specific characters)

My function generates a result that looks like this: given output For comparison, consider the example string below: var string = '    111   1   1\n 1111111 1 \n   &nb ...

What is the most efficient way to perform an inline property check and return a boolean value

Can someone help me with optimizing my TypeScript code for a function I have? function test(obj?: { someProperty: string}) { return obj && obj.someProperty; } Although WebStorm indicates that the return value should be a boolean, the TypeScript compil ...

The battle of promises versus async await in Koa middleware

In an attempt to create a Koa middleware, I am faced with the decision of how to proceed based on certain conditions. If the condition is met, I want to move on to the next middleware. If it is not met, I need to stop the flow. Two possible approaches invo ...

Using JavaScript to retrieve data from a JSON file and showcase it on a jQuery mobile webpage

I am struggling to retrieve JSON data from a PHP URL using JavaScript and display it within a JQuery mobile "li" tag as a category list. Despite spending the last 8 hours on it, I can't seem to get it working using the code provided below. Any help wo ...

Organizing a list based on the text within span elements using either jQuery or underscore

I'm a bit confused about how to arrange an unordered list by the content of the span within each list item. Here is my HTML code: <ul id="appsList"> <li><span>aa</span> <span class="sort">androi ...

Align text to the right and do not include any images

I am attempting to align the images back to the left under the title, while only floating the description text to the right. I am struggling with clearing the image floats. HTML: <div class="title">System Displays</div> <div class="descrip ...

Error encountered while submitting ajax request to server

When I click a button, a function is triggered with the argument insertSongPlay(newSong.songID);. After logging the value of newSong.songID, which is 90 as desired, an ajax call is made: function insertSongPlay(songID) { $.ajax ({ type: " ...

Creating a Server-Side Rendered application from scratch

Currently, we are in the process of developing a Nuxt application using npm run generate and deploying it as a Static Site Generator (SSG). However, an issue has arisen where the application is being built as a Client-Side Rendered (CSR) app instead of Ser ...

Transitioning from CRA to Gatsby caused issues with JSS plugins

When working with `create-react-app`, I utilized `react-jss` because the `jss-plugin-expand` plugin was not included by default. I had `` set up and everything was functioning properly. However, upon switching to Gatsby, the exact same configuration stoppe ...

Discovering the method to incorporate a data-icon attribute within select options using vue.js

UPDATE before modification dataIcon: " @/images/flag-ukraine.svg" after modification dataIcon: require("@/assets/svg/flag-ukraine.svg"), notable change with require() I am using Materialize CSS select. When I use a URL for dataIcon ...

Tips for notifying the parent component when the state of a third-party child component is updated

Utilizing a third party RN component. The component is implemented as: <Component ref={comp => (this.comp = comp)} ... Through this component, data can be accessed like so: this.comp.state.height As the third-party component is integrated into ...

React's input onChange event does not trigger for the second time. It only works the first time

Recently, I developed a React JS application to import images from external sources and process them. To handle the user's onChange event, I utilized the onChange attribute to execute my handleChange function. However, I encountered an issue where it ...