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>'.

     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

The property 'owlDateTimeTrigger' cannot be bound to 'span' as it is not recognized

I have integrated the OwlDateTimeModule into my smart-table-datepicker component. Although I imported it in my smart-table-datepicker.module file, I am still encountering errors. What could be causing this issue? smart-table-datepicker.module.ts import { ...

Cursor vanishes until mouse movement detected (Chrome browser)

In the HTML page I created, the mouse cursor is initially set to none. However, there are certain circumstances where I need it to switch to crosshair. The issue I am facing is that the cursor does not appear unless the user moves the mouse. If the mouse r ...

Showing and hiding nested Form Group validation in Angular 4 is a crucial feature that can improve

I have been exploring Angular 4 validation recently. Currently, I am working with a reactive form that contains two radio buttons and two form groups. The behavior I'm trying to achieve is when the user selects the first radio button, it removes valid ...

Unlocking the secrets of extracting data from navigateOptions within the Navigation Drawer

Having some trouble accessing data from props in my Sidebar component, specifically using Navigation Drawer feature. How can I retrieve the text "xd" from navigationOptions or pass an object to access and read it correctly? contentComponent: props => &l ...

Using Selenium WebDriver in JavaScript to Extract Text from an Array

During my experimentation with Selenium webdriver in javacript, I encountered a challenge when trying to extract text from an array of WebElements (specifically cells within a table). The usual command getText() did not work as expected when attempting to ...

Obtain SVG icons seamlessly in Next.js

My goal was to dynamically retrieve SVG icons, and I discovered a method to achieve this. However, it seems like I have made some errors along the way. Can you point out where I am going wrong? Icon.js import React from "react"; import { ReactCo ...

Struggling with setting up eslint in my typescript project

Below is the contents of my package.json file: { "devDependencies": { "@typescript-eslint/eslint-plugin": "^5.13.0", "@typescript-eslint/parser": "^5.13.0", "airbnb": "^0.0.2&qu ...

Switch out either even or odd divs within a container

I need help figuring out how to alternate the background colors of divs within a container. I want the first one to have a red background, the second to have blue, the third red again, and so on... Here is the code I currently have: <div>...</di ...

Having trouble with Isomorphic fetch not functioning properly for external requests?

EDIT: I am trying to determine why the response does not include the requested data and whether it is due to missing libraries or the format of my fetchUrl variable. Hello, I am attempting to utilize the isomorphic fetch method for making AJAX requests bu ...

I'm looking to update the className to "active" on an li element when the exact route is active in

Is there a way to change the parent li className to active when a route is clicked? Any assistance would be greatly appreciated. The issue is that the li element is the parent of the ROUTER->LINK. import React, {Component} from 'react'; import ...

What is the best way to incorporate vertical scrolling into a React material table?

I'm having trouble getting vertical scroll to work with my material table in React Typescript. Horizontal scroll is functioning properly for large data, but I'm stuck on implementing the vertical scroll. Here's my code: {isLoading ? ...

Leverage the power of require() beyond the confines of Node

I'm currently exploring how to integrate an Angular.js application with Node.js. At the moment, I have the following code in the file MY-PROJECT/public/js/controllers.js function LoginController( $scope ) { // fetch waiters var Waiter = require( ...

Implementing Bootstrap in Wordpress using functions.php

The code snippet below is stored in my functions.php file within a Child theme directory. <?php function theme_styles() { wp_enqueue_style( 'bootstrap_css', get_template_directory_uri() . '/bootstrap.min.css' ); wp_enqueue_ ...

Requesting the user to repeatedly input their birth year until it is less than the current year

Can anyone help me figure out how to display a prompt until the user enters a birth year that is less than the current year? I've tried using a loop in my code, but I'm having trouble getting it right. Any assistance would be greatly appreciated. ...

Unlocking the WiFi Security Key and Accessing Connected Devices with Javascript

When utilizing the command line netsh wlan show interfaces, it displays various information. However, I am specifically interested in extracting the data Profile : 3MobileWiFi-3D71. My goal is to retrieve only the content after the : so that ...

Declaring a function within a conditional statement

I recently came across a code sample in the book You Don't Know JS: Scope & Closures that is puzzling to me. "Function declarations that appear inside of normal blocks typically hoist to the enclosing scope, rather than being conditional as this ...

Refreshing a view in Laravel after a successful insertion using JQuery Ajax

I have been successfully inserting records into a table using jQuery ajax, and receiving a flash message confirming the successful insertion. However, I am now facing an issue where I do not know how to reload the table to reflect the changes after the rec ...

Using jQuery to select the third element from every group of six

I am attempting to select the 3rd .foo element out of every set of 6. To clarify, here is a brief example: 1 2 3 (this) 4 5 6 1 2 3 (this) 4 5 6 and so on... So far, I have only managed to target every 3rd element, which is not exactly what I need beca ...

Ordering request parameters in OAuth2 URL with npm passport can be achieved by following a specific method

I have successfully utilized Oauth2 strategies like Github and Twitter to log in to a web application using npm passport. Now, I am interested in logging in using the new global id authentication. You can explore it here ; it's really amazing. Whil ...

Angular 8's array verification feature lacks the ability to recognize preexisting elements

I've been trying to add and delete items in an array when a user selects or deselects the same item. However, it appears that either my array is not working properly or there is a bug in my code causing it to fail. <div class="grp-input"> ...