Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep the state of the Material-UI AutoComplete when the component re-render?

I'm using Material-UI v4 AutoComplete component with renderOption prop to render a checkbox item option, However the problem is when onChange event fires it updates a hook in the parent component and results a render to the child and thus the state of the component and the state of selected items are lost which leads to inconsistency in the UI and the logic, How can I prevent such scenario while rendering!

export default function CheckboxesTags() {
  return (
    <Autocomplete
      multiple
      id="checkboxes-tags-demo"
      options={top100Films}
      disableCloseOnSelect
      getOptionLabel={option => option.title}
      onChange={(e, values)=> {
          setMoveisFilter(values); // it calls the setter of the hook at the parent component

      }}
      renderOption={(option, { selected }) => (
        <React.Fragment>
          <Checkbox
            icon={icon}
            checkedIcon={checkedIcon}
            style={{ marginRight: 8 }}
            checked={selected}
          />
          {option.title}
        </React.Fragment>
      )}
      style={{ width: 500 }}
      renderInput={params => (
        <TextField
          {...params}
          label="Checkboxes"
          placeholder="Favorites"
          fullWidth
        />
      )}
    />
like image 567
Omar Hamed Avatar asked Sep 12 '25 10:09

Omar Hamed


1 Answers

https://material-ui.com/api/autocomplete/ getOptionSelected prop is what you're looking for e.g getOptionSelected = (option, values) => option._id === values._id

like image 191
Kong Avatar answered Sep 14 '25 02:09

Kong