Personalize Autocomplete CSS based on the TextField input in React Material UI when a value is present

In my current project, I am utilizing React Material Autocomplete fields, which includes a nested TextField. I have successfully implemented standard styles for when the field is empty and only the label is visible, as well as different styles for hover effects. However, I am facing a challenge in applying the same hover styles to the entire Autocomplete box (not just the TextField element) when the TextField contains a value. I am struggling to find a solution for this issue. Below is the code for my Autocomplete component and the CSS styles that are currently in use. Can anyone provide assistance on how I can achieve this?

Autocomplete Code

const renderComponentList = (componentList, isDisabled, name, label) => (
    componentList &&
    <Autocomplete
        classes={{
            root: classes.root,
        }}
        options={componentList}
        disabled={isDisabled}
        name={name}
        getOptionLabel={(option) => option.name}
        onChange={
            (event, value, reason) => {
                this.handleAutocompleteChange(name, value);
            }
        }
        style={{width: '100%'}}
        renderInput={
            (params) =>
                <TextField
                    {...params}
                    name={name}
                    label={label}
                    variant="outlined"
                />
        }
    />
);

CSS Styles

export const styles = theme => ({
    // Autocomplete option styles
    root: {
        color: '#FFFFFF',
        backgroundColor: '#303039',
        opacity: 0.6,
        "&:hover": {
            backgroundColor: '#1E1E24',
            borderRadius: '5px',
            opacity: 1,
        },
        "&:focus-within": {
            backgroundColor: '#1E1E24',
            borderRadius: '5px',
            opacity: 1,
        },
        // Need help with styling the Autocomplete when the input has a value, not working as intended
        // "& input[value]:not([value=''])": {
        //     backgroundColor: '#1E1E24',
        //     borderRadius: '5px',
        //     opacity: 1,
        // },
        "& .MuiOutlinedInput-notchedOutline": {
            border: '1px solid #484850',
        },
        "&:hover .MuiOutlinedInput-notchedOutline": {
            border: '1px solid #484850',
        },
        "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
            border: '1px solid #484850',
            borderRadius: '5px 5px 0 0',
        },
        "& .MuiInputLabel-outlined": {
            color: '#FFFFFF',
        },
        "& .Mui-disabled": {
            opacity: 0.6,
        },
        "& .Mui-disabled .MuiOutlinedInput-notchedOutline": {
            border: '1px solid #484850',
        },
    },
});

Answer №1

After some troubleshooting, I successfully resolved the issue by creating a new class to apply the desired style only when a specific value was present. This involved conditionally rendering it within the Autocomplete element based on the state at hand.

In order to achieve this conditional rendering of the class, I opted to pass in stateVal as one of the props in my function. Subsequently, I made a modification to the Autocomplete classes property by altering the root line to:

root: stateVal ? classes.rootHasVal : classes.rootHasNoVal,

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

What is the reason that elements with % properties totaling 100% do not align next to each other?

I've been attempting to arrange two blocks side by side within another block, but they just don't seem to fit together smoothly. What could be causing this issue? .container {height: 200px; width: 400px; background:darkgrey;} .left {height: 100% ...

Ways to determine the height of a row within a flexbox

Is it possible to obtain the height of each row within a flexbox container using JavaScript? For instance, if there are 3 rows in the container, can I retrieve the height of the second row specifically? ...

jquery expanding the width of the final element

Is there a way to increase the width of the last 'th' in a string? I want it to be the current width plus 20px. Here is the code on Fiddle var header="<th id='tblHeader_1' style='width: 80px;'><span>Id</span&g ...

Utilize Sass @extend to incorporate imported CSS files in the build process

In my development setup, I have a global CSS file that houses all of the generic CSS styles. My goal is to extend the classes from this global CSS file in any of my SCSS files. However, when I attempt to do so, I encounter an error stating that the .xyz c ...

Attempting to locate the element's position using Selenium in Python

quem_esta_sacando = driver.find_elements_by_xpath("//div[@class='gameinfo-container tennis-container']/div[@class='team-names']/div[@class='team-name']") this is how I located the correct class, but now I want to ...

The placeholder feature seems to be malfunctioning when it comes to entering phone numbers in a react

I am working on a MUI phone number form field. I want the placeholder to show up initially, but disappear when the user starts typing. How can I achieve this functionality in my code? import React from "react"; import MuiPhoneNumber from " ...

Completing the remainder of the page with CSS styling

Currently, I have three Divs positioned absolutely on the page - leftDiv, middleDiv, and rightDiv. The middleDiv has a width of 900px, which is fine. However, I need the leftDiv and rightDiv to fill the remaining space on the left and right sides, regardle ...

Utilizing iconClassName for creating material-ui Floating Action Buttons

Is there a way to use the 'iconClassName' prop of FloatingActionButton to display an icon inside it without directly including the icon component? I am aware that I can assign an icon using this method: import IconMenu from 'material-ui/svg ...

Having Trouble with React-Text-Mask and Material UI Integration

After trying numerous different methods, I am still unable to get react-text-mask to work with material UI. Here is my latest attempt: import React from 'react'; import { TextField } from "@mui/material"; import {MaskedInput} from " ...

The Bootstrap navigation bar isn't displaying properly on mobile devices

Help! My Bootstrap navbar is not working properly on mobile view. The menu icon shows up but when clicked, no items are displayed. Here is the HTML code for my navbar: <header class="header_area"> <div class="main-menu"> ...

Centered Bootstrap 4 modal with responsive width

Struggling to create a BootStrap 4 Modal that is centered in the screen and adjusts its width based on content? You're not alone. Despite trying different approaches like the container fluid and CSS methods, achieving a variable width modal is proving ...

Reorganize a list based on another list without generating a new list

Among the elements in my HTML list, there are items with text, input fields, and tables. I also have a specific order list like [3,1,2,0]. Is it feasible to rearrange the items in the HTML list on the page based on this order list without generating a new ...

Fire the props.onChange() function when the TextField component is blurred

Currently, I am in the process of developing a NumberField component that has unique functionality. This component is designed to remove the default 0 value when clicked on (onFocus), allowing users to input a number into an empty field. Upon clicking out ...

Type of element returned

Is there a way to retrieve the element type? I'm interested in applying the style of a class to HTML5 elements without using the class attribute. <!DOCTYPE> <html> <head> <title>My page</title> </head& ...

Is there a way to alter the variant or background of a clicked button exclusively through reactjs? If so, how can I make it happen?

My goal is to change the variant of a Material UI button from outlined to contained or simply change its background color when it is clicked. I am unable to use the onFocus property due to conflicts with another component. Here is my current method, but ...

Having difficulty adjusting the width of a div element

I've been struggling to adjust the width of the div assigned with the colors class, whether in percentage or pixels. var colors = ["RED", "GREEN", "BLUE", "YELLOW", "PURPLE"]; for (var h = 0; h <= 4; h++) { for (var i = 0; i <= colors.lengt ...

Dynamically Growing Navigation Bar Elements with Nested Subcategories Based on Class Identification

Let's say you have a menu bar structured as follows: <nav> <ul class="nav"> <li class="menu1"><a href="#">Menu Item 1</a></li> <li class="menu2"><a href="#">Menu Item 2</a> <ul& ...

Ways to identify when a specific react component has been clicked

Currently working on developing a klondike game with 4 empty stacks at the start of the game. The initial page layout resembles the first image provided in the link. I am facing an issue where I cannot determine which component was clicked when clicking on ...

Align the div to the left with text or a paragraph displayed on the right side

Check out my js fiddle below: https://jsfiddle.net/9yj63s3f/ Here is the CSS code snippet: .viddiv{ float:left; width:50%; } .vidholder{ position:relative;height:0;padding-bottom:50%; width:50%; float:left; } iframe{ position:abso ...

Styling the select dropdown border in Google Chrome

I am encountering an issue with styling HTML select options in Chrome. Despite successfully applying borders to each option in Firefox, I cannot get it to work in Chrome. Can anyone advise on how this can be achieved? <select id="sortingOptions" class= ...