Is there a way to align the choices in a MUI autocomplete to the center and surround them with a border?

I've been struggling to center the options in a MUI autocomplete and wrap each option in a border. I've tried multiple methods without success, including adding it to inputProps and using a style paper component.

const PlacementCell = ({ value, placements, notAvailable = false, readOnly = false }: PlacementCellProps): ReactElement => {
  const { palette, spacing } = useTheme();
  const [selectedPlacement, setSelectedPlacement] = useState<Placement | undefined>(value || placements[0]);

  const handlePlacementChange = (event: React.SyntheticEvent, newValue: Placement | null) => {
    if (newValue !== null) {
      setSelectedPlacement(newValue);
    }
  };

const CustomListbox = styled('ul')({
  [`& .${autocompleteClasses.option}`]: {
    display: 'flex',
    justifyContent: 'center',
  },
});

  return (
    <Stack
      direction="row"
      height={1}
      alignItems="center"
      spacing={2}
      justifyContent="space-between"
    >
      <Autocomplete
        options={placements}
        getOptionLabel={(option) => option.placementName}
        renderInput={(params) => (
          <TextField
            placeholder="Select"
            {...params}
            InputProps={{
          ...params.InputProps,
          disableUnderline: true,
            }}
            inputProps={{
              ...params.inputProps,
              style: { textAlign: 'center' },
            }}
            sx={{
              [`& .${autocompleteClasses.inputRoot} .MuiInput-input`]: {
                padding: '12px',
              },
              variant: 'bodySmall.default',
              [`& .${autocompleteClasses.popupIndicator}`]: {
                right: 12,
                ['&:hover']: {
                backgroundColor: 'transparent',
                },
              },
            }}
          />
        )}
        // PaperComponent={CustomPaper}
        fullWidth
        disableClearable
        onChange={handlePlacementChange}
      />
    </Stack>
  );
};

If you need a visual reference, check out this image: https://i.sstatic.net/DIQcfY4E.png

Any suggestions would be greatly appreciated!

Answer №1

section, consider incorporating the renderOption function in conjunction with the slotProps route. By doing so, you gain the flexibility to customize each list item using any MUI component. Check out this example of implementing the renderOption: MUI Autocomplete renderOption Example. This setup allows for selecting items even when clicking outside the box within the same row. While slotProps also supports this functionality, it may necessitate additional CSS styling. For a scenario where users must select inside the box and not on the row itself, consider moving the {...params} from the box to the Typography element. This adjustment should ensure that selection only occurs when clicking within the box area.

Answer №2

Utilizing the slotProps feature within your Autocomplete component is recommended, as detailed in this post: https://example.com/a/12345678

To implement this, follow a structure similar to the one below:

<Autocomplete
...
  slotProps={{
    paper: {
      sx: {
        '& .MuiAutocomplete-listbox': {
          '& .MuiAutocomplete-option': {
            display: 'flex',
            justifyContent: 'center',
            border: '1px solid lightgray',
            margin: '5px'
          },
        },
      },
    },
  }}
/>

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

When integrating Material-UI into my SPFx project, I am encountering numerous errors

I am currently facing issues while trying to implement a button using Material-UI in my project. The JavaScript version I am using is 4.1.3 and the npm version is 6.14.10. To install Material UI, I used the following command: npm install @material-ui/core ...

Is there a way to prevent hyphens from appearing in Outlook email messages?

I have encountered an issue while developing an email template. When viewed in Outlook emails, the words break into two lines with hyphens. I have attempted various CSS properties on the 'td' tag, but to no avail. Is there no way to control this ...

How can you activate a checkbox by simply clicking anywhere on the row?

I am working with a list of checkboxes and currently, the user can only activate a checkbox by clicking directly on the checkbox itself. Is there a way to allow users to activate a checkbox by clicking anywhere in the same row as the checkbox? return( ...

How can I effectively update Bootstrap 4 in a Rails environment?

After attempting to update my Rails 5 project from Bootstrap 4 Alpha 6 to the final version 4.0.0, I confirmed that the v4.0.0 gem was installed (with the alpha version gem uninstalled). However, upon running my project in development mode, I discovered th ...

The border is not properly containing the element within

I've been struggling to create a menu with no luck. My goal is to add a border to all my li elements, but the border consistently appears only at the bottom. Is there a way to make the border wrap around the entire li element? Check out my code here: ...

Tips for Making Stylish Text using Gradient and Emboss Effects in CSS

I'm on a quest to achieve a unique visual impact for text using CSS that combines both a gradient and embossing. Take a look at the image I've included to see the effect I'm striving for. Check out this Example Photo: https://i.sstatic.net/ ...

Addressing Image Issues in CSS Grid

I'm struggling to position two images in different sections of a grid layout without overlapping them. I've attempted referencing the images by both their class and id, but they continue to occupy the same grid space. Referencing the images by ...

Issues with the webpack-dev-server and React

I was just reading up on Webpack and the moment came for me to start using it, but I ran into an error. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a09180b471e1f1e ...

an online platform design

I am currently working on building a webpage, but I am facing some issues with the layout. Specifically, I am unable to make the div automatically adjust its size (particularly the height). Here is the code that demonstrates the problem: <!DOCTYPE html ...

Adding new elements without repeating them

Having an issue with appending an element to the end of a span on my webpage. The problem arises when there are multiple spans, causing the element to duplicate itself across all spans instead of going only at the very end of the last span. Any suggestions ...

Generate a pair of rows using input-prepend

I am attempting to place two buttons on either side of the search field, so I implemented the following code: <div id="fixtures-filter"> <div class="input-group-btn"> <div class="input-group-prepend"><button type="button" class= ...

The styles of Material UI components are not being properly applied when used within the react-frame

I have been working on implementing a Persistent drawer feature from the demo code provided in Material UI V3. You can find the link below: To make it appear in a different iframe, I decided to wrap it inside a react-frame-component. However, when I tried ...

Issue encountered while passing parameters using history.push() in react-routing with ReactJS

Trying to send props to another React component using history.push() is causing me some trouble. Here's the code I have: history.push({ pathname: `/tickets/solveticket`, state: { ticket: this.props.ticketInfo, user: this.props.currentUs ...

Retrieving Content within <b></b> Tags from an RSS Feed XML (with Javascript/React)

After parsing an RSS Feed from Upwork, I have extracted job item data points such as title and link. However, a significant amount of the necessary information about each job (category, skills, etc) is buried within the "content" data item as one large blo ...

Thumbnails failing to line up in a continuous row

Having an issue creating a row with 3 thumbnails as they are not aligning in a single row, instead each thumbnail is going into a different row. echo "<table>"; echo "<tr>"; echo "</tr>"; while($r ...

What is the best way to utilize mat-paginator for handling multiple requests instead of fetching all the data at once?

In our project, we have a view that pulls all the necessary information (in JSON format) for the mat-paginator display. However, there is an issue with speed as the list grows daily with thousands of new rows. One potential solution is to fetch data from ...

Adding commas to page numbers in pagination using MUI: A guide

Currently, I am working on a pagination system using MUI. Here is an image for reference: https://i.stack.imgur.com/7AudV.png My goal is to incorporate commas in the number of pages, such as displaying it as 39,233 ...

Having trouble extracting data from Moz Bar through selenium using Python?

Having trouble retrieving the spam score from Moz bar using Selenium WebDriver? I've attempted various methods such as XPath, class, and tag name without success. Any assistance would be greatly appreciated: from selenium.webdriver.common.by import By ...

Splitting hyphenations

Check out my Codepen project I'm attempting to prevent word-breaks inside my .threadTitle class by using display: inline-block. While this solution works, the addition of a hyphen between two letters still causes a break. https://i.sstatic.net/q6ZMk ...

Is the value in React constantly changing?

I have encountered an issue with my code while trying to create a constant to retrieve old messages from my chat. The const seems to be changing its value unexpectedly, even though I do not call it except in the console logs. const oldMessages = this.stat ...