Henrique Ricci
Henrique Ricci

Reputation: 33

Autocomplete - MaterialUI - Controled component doesn't work

Basically, I created the autocomplete component and set default value as my state this.state.quest.ansType, but when I change this state, the component result an error: component is changing the default value state of an uncontrolled Autocomplete after being initialized. To suppress this warning opt to use a controlled Autocomplete.

I need this for my update function. When the user selects the register on the database, I will load the options saved on the default value of Autocomplete.

const ansTypes = [
    {
        id: 'T',
        desc: "Texto"
    },
    {
        id: 'M',
        desc: "Multipla Escolha"
    },
    {
        id: 'U',
        desc: "Escolha Única"
    },
];

<Autocomplete className="cb" id={"ansType"} options={ansTypes}
    disableCloseOnSelect
    onChange={obj => this.selectAnsType(obj)}
    defaultValue={this.state.quest.ansType}
    getOptionLabel={option => option.desc}
    renderOption={(option, { selected }) => (
        <React.Fragment>
            <Checkbox
                style={{ marginRight: 8 }}
                checked={selected}
                color={"primary"}
            />
            {option.desc}
        </React.Fragment>
    )}
    renderInput={(params) => (<TextField {...params} label={"Answer Type"} />)}
/>

Upvotes: 3

Views: 2327

Answers (1)

Andrea
Andrea

Reputation: 1316

Basically, you've been changing the default value after the first render, which shouldn't happen. Either you use an uncontrolled Component (-onChange, -value,+defaultValue, +ref) of you use a controlled component (+onChange, +value, -defaultValue, ref->only if needed). DefaultValue should be used for the uncontrolled ones!

Controlled

...


<Autocomplete className="cb" id={"ansType"} options={ansTypes}
    ...
    onChange={obj => this.selectAnsType(obj)}
    value={this.state.quest.ansType}
    ...
/>

Uncontrolled

...
defaultAnsType={...};

myUncontrolledAutocomplete=React.createRef();

<Autocomplete className="cb" id={"ansType"} options={ansTypes}
    ...
    defaultValue={this.defaultAnsType}
    ref={this.myUncontrolledAutocomplete}
    ...
/>
$

Personal Opinion

I'd use the controlled one, because it's easier to understand. On the other hand the uncontrolled component could make your component stateless which could be something you might wanna use in the future.

Upvotes: 6

Related Questions