user944513
user944513

Reputation: 12729

why checkbox is not checked in react?

I am trying to implement Auto complete having checkbox.

https://material-ui.com/components/autocomplete/#autocomplete enter image description here

but when I am implementing same component in final-form I am not able to checked my option why ?

here is my code https://codesandbox.io/s/relaxed-breeze-hv58o

<Autocomplete
      {...rest}
      multiple={multiple}
      disableCloseOnSelect={true}
      options={
        multiple
          ? maxReached
            ? []
            : options.filter(option => !value.includes(option.value))
          : options
      }
      defaultValue={
        multiple
          ? options.filter(option => value.includes(option.value))
          : options.find(option => option.value === value)
      }
      onChange={
        multiple
          ? (_e, values) => {
              setMaxReached(value.length >= max - 1);
              onChange(values.map(option => option.value));
            }
          : (_e, option) => onChange(option.value)
      }
      getOptionLabel={option => option.label}
      noOptionsText={
        maxReached
          ? formatMessage({ id: "components.autocomplete.max" }, { max })
          : formatMessage({ id: "components.autocomplete.no" })
      }
      renderOption={(option, { selected }) => (
        <React.Fragment>
          <Checkbox
            icon={icon}
            checkedIcon={checkedIcon}
            style={{ marginRight: 8 }}
            checked={selected}
          />
          {option.label}
        </React.Fragment>
      )}
      renderInput={params => (
        <TextField
          {...params}
          {...restInput}
          label={label}
          placeholder={placeholder || ""}
          helperText={
            hasError ? formatMessage({ id: error }, { label }) : helperText
          }
          error={hasError}
          fullWidth
        />
      )}
    />
  );
};

Upvotes: 0

Views: 1716

Answers (1)

Mohamed Youssef
Mohamed Youssef

Reputation: 161

You have some issues with your code (fixed version):

  1. You are calling onChange that makes React-Final-Form re-render, which leads for Autocomplete component to re-render, and remove the select state. To fix this, you will have to use getOptionSelected option.
getOptionSelected={(option, value) => {
    return option.value === value.value;
}}
options={ 
    options
}
onChange={(_e, values) => {
    onChange(values);
}
  1. You are filtering options based to Autocomplete component, so selected option gets filtered out. so from this:
options={
  multiple
  ? maxReached
  ? []
  : options.filter(option => !value.includes(option.value))
  : options
}

To

options={
   options
}

Upvotes: 4

Related Questions