Reputation: 1611
I'm using the Autocomplete component as in the country example, but decorated with the InputAdornment component in order to show the flag of the select country.
Here the working code:
The problem: after picking a country, if the user clicks exactly on the flag, country's name is selected. And, if the user clicks on the remaining part of the Autocomplete, the Popper is showing up (as expected and that's totally ok).
Current behaviour:
MY GOAL: I'd like to open the Autocomplete Popper even when clicking on the flag.
Expected behaviour:
I tried to use the option disablePointerEvents in the InputAdornment parameters, but nothing changed. I tried the same on a pure Textfield MUI component and it worked, so it maybe it is something related to Autocomplete only.
Is there a workaround for this issue?
Same issue here
Upvotes: 1
Views: 3341
Reputation: 81106
One solution is to control the open
state of the Autocomplete
using the open
, onOpen
, and onClose
props and then add an onClick
(instead of disablePointerEvents
) to the InputAdornment
to open the Autocomplete
.
Here is a working example based on your sandbox:
import * as React from "react";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
import InputAdornment from "@mui/material/InputAdornment";
export default function CountrySelect() {
const [value, setValue] = React.useState(null);
const [open, setOpen] = React.useState(false);
return (
<Autocomplete
id="country-select-demo"
value={value}
onChange={(event, newValue) => {
setValue(newValue);
}}
sx={{ width: 300 }}
options={countries}
autoHighlight
open={open}
onOpen={() => setOpen(true)}
onClose={() => setOpen(false)}
getOptionLabel={(option) => option.label}
renderOption={(props, option) => (
<Box
component="li"
sx={{ "& > img": { mr: 2, flexShrink: 0 } }}
{...props}
>
<img
loading="lazy"
width="20"
src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
alt=""
/>
{option.label} ({option.code}) +{option.phone}
</Box>
)}
renderInput={(params) => (
<TextField
{...params}
label="Choose a country"
inputProps={{
...params.inputProps,
autoComplete: "new-password" // disable autocomplete and autofill
}}
InputProps={{
...params.InputProps,
startAdornment: value ? (
<InputAdornment position="start" onClick={() => setOpen(true)}>
<img
loading="lazy"
width="48"
src={`https://flagcdn.com/w20/${value.code.toLowerCase()}.png`}
srcSet={`https://flagcdn.com/w40/${value.code.toLowerCase()}.png 2x`}
alt=""
/>
</InputAdornment>
) : null
}}
/>
)}
/>
);
}
Upvotes: 1