Isaac
Isaac

Reputation: 261

How to prevent re-render while keeping state when using Material UI Autocomplete with multiple options?

I am using Material UI's Autocomplete component with multiple options enabled. I need to be able to select multiple options and update the state every time the value changes. For this, I am using the onChange prop. This works fine when using only one option. But with multiple options enabled, every time I select an option, the component re-renders and I am unable to select a second option.

This is the onChange handler:

const handleUserAssignEvent = (event, value) => {
   setSelectedUsers(value)
}

This is the Autocomplete component:

const renderUserAssignmentForm = () => {
 const icon = <CheckBoxOutlineBlankIcon fontSize="small" />
 const checkedIcon = <CheckBoxIcon fontSize="small" />
 return (
         <Autocomplete
            multiple
            id="usersList"
            options={filteredUsers ?? users ?? []}
            noOptionsText="No users found..."
            disableCloseOnSelect
            onChange={(event, value) => handleUserAssignEvent(event, value)}
            getOptionLabel={(option) => option.fullname}
            renderOption={(option, { selected }) => (
              <>
                <Checkbox
                  icon={icon}
                  checkedIcon={checkedIcon}
                  style={{ marginRight: 8 }}
                  checked={selected}
                />
                {option.fullname}
              </>
            )}
            style={{ width: 500 }}
            renderInput={(params) => (
              <TextField
                {...params}
                variant="outlined"
                label="Users"
                placeholder="User lookup..."
              />
            )}
          />
)}

What can I do to be able to update the state without having the Autocomplete component re-render on every change and be able to select multiple options?

Upvotes: 0

Views: 2729

Answers (1)

Ahmed Mohamedeen
Ahmed Mohamedeen

Reputation: 389

I've replicated your example here and there was no problem with selecting multiple options.

Your problem might be that the options prop filteredUsers and users are related/change with selectedUsers. Or the whole component which contains renderUserAssignmentForm being unmounted and mounted again.

Upvotes: 1

Related Questions