MUI Autocomplete - add clear button

Hello,

I’ve added a MUI Autocomplete to our JSON Forms React app. Everything is working as I would like apart from one thing - I can’t get the clear button to show up. In practice this means users are likely to delete the text leaving an empty string for that property, rather than the property being undefined.

Any suggestions of how I can fix this?

Thanks in advance.

Paddy

import React, { ReactNode } from ‘react’;
import { EnumCellProps, EnumOption, WithClassname } from ‘@jsonforms/core’;

import {
Autocomplete,
AutocompleteRenderOptionState,
Input,
FilterOptionsState
} from ‘@mui/material’;
import merge from ‘lodash/merge’;

export interface WithOptionLabel {
getOptionLabel?(option: EnumOption): string;
renderOption?(props: React.HTMLAttributes, option: EnumOption, state: AutocompleteRenderOptionState): ReactNode;
filterOptions?(options: EnumOption, state: FilterOptionsState): EnumOption;
}

export const CustomMuiAutocomplete = (props: EnumCellProps & WithClassname & WithOptionLabel) => {
const {
data,
className,
id,
enabled,
uischema,
path,
handleChange,
options,
config,
getOptionLabel,
renderOption,
filterOptions
} = props;
const appliedUiSchemaOptions = merge({}, config, uischema.options);

const handleChangeExtended = (ev, value: any) => {
    handleChange(path, value)
}

return (
    <Autocomplete
        className={className}
        id={id}
        disabled={!enabled}
        value={data || ''}
        onInputChange={(event, value) => handleChangeExtended(event, value)}
        freeSolo
        selectOnFocus
        clearOnBlur
        fullWidth
        options={options.map((option) => option.value)}
        style={{ marginTop: 16 }}
        renderInput={params => (
            <Input
                style={{ width: '100%' }}
                type='text'
                inputProps={params.inputProps}
                inputRef={params.InputProps.ref}
                autoFocus={appliedUiSchemaOptions.focus}
                disabled={!enabled}
            />
        )}
        renderOption={renderOption}
        filterOptions={filterOptions}
    />
);

};

Hi @paddy.hudson,

This is more of a Material UI question than a JSON Forms question. I think the issue here is the usage of Input. If instead of Input you would use TextField, then the clear button would already be provided by Material UI, you can check the Material UI documentation for examples. If you still want to use Input instead of TextField, then you need to manually add the clear button yourself, for example by using an endAndornment.

I would recommend using a TextField.