The styling of the Material UI autocomplete listbox does not affect its appearance

I am working on an autocomplete feature that groups items by titles. I am trying to adjust the height of the first group to be different from the rest, but I am facing some challenges since there is no unique identifier for the ul component. To work around this, I have used the following method to update the styling:

'& .MuiAutocomplete-listbox > li:nth-of-type(1) > ul': {
        maxHeight: '208px',
        overflowX: 'hidden',
        overflowY: 'auto',
      },

However, it seems that this approach is not having any impact.

In my search for a solution, I stumbled upon a reference to a potential bug in Material-UI at https://github.com/mui/material-ui/issues/32540. Unfortunately, I could not find any further details about this issue.

If anyone has any insights or leads on how to address this problem, I would greatly appreciate your help. Thank you in advance.

Answer №1

To uniquely style the initial Group Header, you can implement some strategies outlined in the MUI documentation.

Enabling the Autocomplete Group By feature showcased in the example titled With categories, a live demo and source code are provided for reference.

The MUI illustration involves:

1. options

An array of options where each option object includes a firstLetter property:

const options = top100Films.map((option) => {
    const firstLetter = option.title[0].toUpperCase();
    return {
        firstLetter: /[0-9]/.test(firstLetter) ? '0-9' : firstLetter,
        ...option,
    };
});

2. Autocomplete options property

The Autocomplete options should be set to an array of options arranged by the firstLetter.

...

<Autocomplete
    id="grouped-demo"
    options={options.sort((a, b) => -b.firstLetter.localeCompare(a.firstLetter))}
    groupBy={(option) => option.firstLetter}

    ...

To execute correct sorting (

options.sort((a, b) => -b.firstLetter.localeCompare(a.firstLetter))
), it should happen before the component's return statement. The sorted result should be stored in a variable (e.g. sortedOptions) with component-level scope. This ensures that sortedOptions is accessible to any function within the component using Autocomplete. With this update in place, the code would appear as follows:

...

<Autocomplete
    id="grouped-demo"
    options={ sortedOptions }
    groupBy={(option) => option.firstLetter}

    ...

3. Autocomplete renderGroup property

The renderGroup should refer to a component featuring a customized GroupHeader element styled with styled.

...

renderGroup={(params) => (
    <li key={params.key}>
        <GroupHeader>{params.group}</GroupHeader>
        <GroupItems>{params.children}</GroupItems>
    </li>
)}

...

The First Group Header

By combining these three concepts, the firstLetter property and styling props from styled can be leveraged to identify the First Group Header. Modify the GroupHeader component definition in the MUI example as shown below:

const GroupHeader = styled('div')(({ theme, ...props }) => {
    let isFirstGroup = sortedOptions[0].firstLetter === props.children;

    return {
        position: 'sticky',
        top: '-8px',
        height: isFirstGroup ? '100px' : 'inherit', // Sample adjustment for the First Group.
        padding: '4px 10px',
        color: theme.palette.primary.main,
        backgroundColor:
            theme.palette.mode === 'light'
                ? lighten(theme.palette.primary.light, 0.85)
                : darken(theme.palette.primary.main, 0.8),
    }
});

This approach works due to the specific signature of the Autocomplete renderGroup callback function:

Signature:

function( params: AutocompleteRenderGroupParams ) => ReactNode

The Autocomplete provides params to the callback, representing the group to render:

let params = {
    group: a string indicating a group name
    children: a collection of list items belonging to the group
};

When renderGroup iterates through the elements in the array passed to the groupBy property, it supplies the renderGroup callback with a param object resembling this structure (assuming a group name starts with the letter 'A'):

param = {
    group: 'A',
    children: ...
};

Hence, the line

<GroupHeader>{params.group}</GroupHeader>
actually renders
<GroupHeader>{'A'}</GroupHeader>
.

Since 'A' is the child of GroupHeader, we can utilize

let isFirstGroup = sortedOptions[0].firstLetter === props.children;
to extract 'A' (props.children === 'A') and compare it with the firstLetter property of the initial element in the sortedOptions array.

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 Intriguing Riddle of HTML Semantic

I've been working on a puzzle presented in the link provided below: HTML Structure Challenge This mind-teaser consists of three questions: Modify the HTML code of the website to enhance its structure as follows: Replace the generic outer div eleme ...

"Create a Material UI input element that spans the full width of the form, includes a formHelper text,

Can anyone help me understand how to effectively utilize the Material UI form input elements? I'm attempting to create a full-width input that includes both a form helper and an endAdornment. After experimenting with both the Input and InputBase opt ...

The Vite manifest could not find the file "app.jsx" in the resources/js directory. Please run "npm run build

Following the guidelines from , I have successfully created a Laravel application with the following specifications: PHP 8.1.2 Laravel 9.33.0 React During development using VITE (npm run dev), everything works smoothly. However, when attempting to build ...

Leveraging the :has pseudo-class in Tailwind along with adjacent sibling selectors

My CSS code is working perfectly as intended. [data-type='transfer']:has(+ [data-type^='sale_']) { opacity: 0.25; } This CSS snippet targets elements with data-type="transfer" that are next to elements containing data attri ...

Learn the method to conceal rows within a table simply by toggling a button

I need a function that will hide the rows below a row with a header and button, and only reveal them when another row with a header and button is clicked. When one of the +/- buttons is clicked, it should hide or expand all the rows with data content. http ...

Transform a <ul> into an <ol> format (replacing bullets with numbers)

This question presents a challenge, but there may be a solution waiting to be uncovered. Presently, I am utilizing the Kendo UI panelbar for developing expandable lists. However, an issue surfaces when employing an <ol> as the sublist - in this scen ...

Page jumping vertically in Chrome upon reload, with Firefox and Internet Explorer functioning properly

Utilizing this jQuery script, I am able to center a website vertically within the browser window if it exceeds the height of the outer wrapper-div, which has fixed dimensions. $( document ).ready(function() { centerPage(); )}; // center page vertic ...

Browser displaying a CSS error: "Invalid property name" while applying pseudo-element :after

I encountered an issue in Chrome and Explorer while attempting to set a CSS property for a pseudo element :after. (I'm trying to create a styled burger nav icon) The error message I received was: 'Unknown property name' This happened wh ...

Creating a fluid side navigation bar in reactjs

Can someone please help me with the following code issue? I am encountering an error related to the script tag when running it in ReactJS, although it works fine in a simple HTML file. Upon starting npm, an error is displayed pointing to line number which ...

Why won't the CSS update in Next.js when the local state variable changes on page load?

I seem to be facing an issue with a variable stored in localStorage that changes when using a toggle button. The color changes correctly upon toggling the button, but upon page refresh, it doesn't display the correct color saved in local storage. Eve ...

Invoke `setState` function in contexts outside of React framework

Is the following approach guaranteed to work correctly within React v18 semantics? The "rules of hooks" only address calling the hook within the component, with no mention of whether it's acceptable to call the dispatcher returned from the ...

align items center with respect to my central element

Describing my issue might be a bit complex, but I'll give it a shot. I'm working on a website and have 3 div elements in the header for my navigation bar (burger menu / logo / social networks). I've used flex display with justify-content: be ...

"Trouble with getting the Twitter Bootstrap dropdown menu to function properly

Currently, I am facing a challenge with my project as the dropdowns on the menu are not functioning properly. Despite having all the necessary files included, it seems like there might be an issue within my code. You can view the page here: (please try t ...

Refresh the react-table when an event occurs

I'm utilizing React and the react-table framework to display and list my data respectively. One issue I am facing is that after creating a new object in my database, I have trouble refreshing the table without navigating away from the view. My query ...

Insert a CSS Class into an HTML div element with JQuery

I'm faced with a bit of a challenge. Here's the scenario: <div class="portItem"></div> <div class="portItem"></div> <div class="portItem"></div> <div class="p ...

Guide on displaying an X mark on a checkbox in AngularJS when the ng-disabled value is set to true

Is there a way to display an X mark in red on checkboxes when the ng-disabled condition is evaluated as true? I am a beginner in Angular.js and would appreciate any assistance. Here is what I have attempted so far: if (module.Name === 'val1' || ...

Ways to prevent the hover state from activating when the mouse is in the corner of a circular QPushButton

I'm working on customizing a QPushButton that has round corners: https://i.stack.imgur.com/g8zfs.png When the mouse hovers over the button, I want to change its style: https://i.stack.imgur.com/SDm79.png To achieve this, I utilized setStyleSheet f ...

Activate modifications in a distinct column?

I've been exploring a solution to achieve a similar functionality where clicking or hovering on headings in a column brings up corresponding text in another column. My idea is to use list items with a carousel for this purpose, but I'm facing so ...

Ways to prevent styles from being overridden by those specified in JavaScript

Some elements on my page have their style dynamically changed by JavaScript. However, I want one of them to maintain its static style without being overridden. Is there a way to specify that the style of this particular element should not be altered? Than ...

Next.js is experiencing difficulty serving dynamic images in real-time

Currently, my project uses Next.js API for the backend and MongoDB for the database. I am faced with the challenge of serving user-uploaded images at runtime, since these files were not available during build time and are not recognized as static files tha ...