How to clear data of AutoComplete Box using OnClick?

2.2k Views Asked by At

I have used material UI AutoCompleteBox here it's Link:https://material-ui.com/components/autocomplete/

My code is:

<Autocomplete
  open={showUniSuggs}
  onOpen={this.props.getUniversityOptions}
  onChange={(event, value) =>
    this.props.handleUniversityChange(value)
  }
  onClose={this.props.onUniversityClose}
  getOptionLabel={(option) => option._id}
  options={universityOptions}
  loading={uniLoading}
  // disabled={disableUniversity}
  renderInput={(params) => (
    <TextField
      {...params}
      label="Search for university"
      fullWidth
      variant="filled"
      margin="dense"
      InputProps={{
        ...params.InputProps,
        endAdornment: (
          <React.Fragment>
            {uniLoading ? (
              <CircularProgress color="inherit" size={20} />
            ) : null}
            {params.InputProps.endAdornment}
          </React.Fragment>
        ),
      }}
    />
  )}
/>

Whenever click on Autocomplete search bar API is called and data is saved on getUniversityOptions Select any Value then we click on the cross icon of Autocomplete search bar and data has cleared. But I want that this data will clear using Onclick function Whenever Click on Button the data will clear. So How it's possible to do it.

1

There are 1 best solutions below

0
Khabir On

you can set value property with empty string to clear the value like

<Autocomplete value={value} .....
<button onClick={() => { setValue('') }} >Clear Value</button>

here is the complete example:

import React from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete, {createFilterOptions} from '@material-ui/lab/Autocomplete';

const filter = createFilterOptions();

export default function FreeSoloCreateOption() {
    const [value, setValue] = React.useState(null);

    return (
        <div>
            <Autocomplete
                value={value}
                onChange={(event, newValue) => {
                    // Create a new value from the user input
                    if (newValue && newValue.inputValue) {
                        setValue({
                            title: newValue.inputValue,
                        });
                        return;
                    }
                    setValue(newValue);
                }}
                filterOptions={(options, params) => {
                    const filtered = filter(options, params);

                    // Suggest the creation of a new value
                    if (params.inputValue !== '') {
                        filtered.push({
                            inputValue: params.inputValue,
                            title: `Add "${params.inputValue}"`,
                        });
                    }
                    return filtered;
                }}
                selectOnFocus
                clearOnBlur
                id="free-solo-with-text-demo"
                options={top100Films}
                getOptionLabel={(option) => {
                    // Value selected with enter, right from the input
                    if (typeof option === 'string') {
                        return option;
                    }
                    // Add "xxx" option created dynamically
                    if (option.inputValue) {
                        return option.inputValue;
                    }
                    // Regular option
                    return option.title;
                }}
                renderOption={(option) => option.title}
                style={{width: 300}}
                freeSolo
                renderInput={(params) => (
                    <TextField {...params} label="Free solo with text demo" variant="outlined"/>
                )}
            />
            <button onClick={() => { setValue('') }} >Clear Value</button>
        </div>
    );
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
    {title: 'The Shawshank Redemption', year: 1994},
    {title: 'The Godfather', year: 1972},
    {title: 'The Godfather: Part II', year: 1974},
    {title: 'The Dark Knight', year: 2008},
    {title: '12 Angry Men', year: 1957},
];