1

I have an Autocomplete component which displays the coutries name and flags as in the example from the MUI doc.

Edit CountrySelect Material Demo (forked)

My goal is simply the following: once the Autocomplete component is clicked, the country's name must be cleared displaying only the placeholder.

I achieved this with a simple onClick event in the renderInput which triggers the following function:

  const handleClear = (e) => {
    e.target.value = "";
  };

If trying the code everything works as expected, apparently. Actually, the clearing happens only when the country's name is clicked, but if a different portion of the component is clicked, like the flag or the dropdown arrow, the country's name is simply focused, not cleared.

In short, here the current behaviour:

current behaviour

and here the expected behaviour: expected

Is there a way to fix this?

2 Answers 2

2

That's behavior occurs because when you click on the flag, the e.target won´t be the input element, but the wrapper div. You can see this just adding a console.log to the handleClear function:

const handleClear = (e) => {
    console.log("clicked TARGET ELEMENT: ", e.target);

    // If you click on the input, will see:
    // <input ...

    // And if you click on the flag, you will see:
    // <div ...
};

If you want to control the input state value and the text value separately, you probably should go with the two states control - check it on MUI docs.

The code will be something like:

export default function CountrySelect() {
  const [value, setValue] = useState(null);
  const [inputValue, setInputValue] = React.useState("");

  const handleClear = (e) => {
    console.log("clicked TARGET ELEMENT: ", e.target);
    setInputValue("");
  };

  return (
    <Autocomplete
      id="country-select-demo"
      disableClearable
      value={value}
      onChange={(event, newValue) => {
        setValue(newValue);
      }}
      inputValue={inputValue}
      onInputChange={(event, newInputValue) => {
        setInputValue(newInputValue);
      }}
      openOnFocus
      sx={{ width: 300 }}
      options={countries}
      autoHighlight
      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"
          placeholder="Choose a country"
          onClick={handleClear}
          InputProps={{
            ...params.InputProps,
            startAdornment: value ? (
              <InputAdornment disablePointerEvents position="start">
                <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
          }}
        />
      )}
    />
  );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great, it works! It is also the correct approach because there is the separation between the value and the text value. Thanks!
0

Instead of using onClick on TextField, you can use onOpen props and pass handleClear function in it. It works then. Selected value gets cleared whenever autocomplete is open.

Working Demo: CodeSandBox.io

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.