Material-ui autocomplete clear value

Kirill picture Kirill · Jan 17, 2020 · Viewed 11.2k times · Source

I have one problem in my react code.

I use Material-ui and redux-form. I have select input like and after change this select i should reset value in . I use action 'change' from react-form and set value for textfield. But label in still remains. Can i clear or reset value in ?

<Autocomplete
    options={list}
    getOptionLabel={option => option.name}
    onInputChange={onChange}
    onChange={onChangeAutoComplete}
    noOptionsText='Нет доступных вариантов'
    loadingText='Загрузка...'
    openText='Открыть'
    renderInput={params => (
        <Field
            {...params}
            label={label}
            name={fieldName}
            variant="outlined"
            fullWidth
            component={renderTextField}
            className={classes.textField}
            margin="normal"
        />
    )}
/>

Answer

Milan Neninger picture Milan Neninger · Jan 21, 2020

Using hooks on the value prop breaks the functionality of the autocomplete component ( at least for me ). Using class, and setting the local state is the same.

Luckily it is a react component, so it have a "key" prop. When the key prop changes, the component is re-rendered with the default values ( which is an empty array since nothing is selected). I used hooks in the parent component and passed the values to the key prop, whenever reset is needed.

<Autocomplete
    key={somethingMeaningful} // Bool, or whatever just change it to re-render the component
//...other props
/>

Hope this helps!