Controlled Multiselect using react hook form

144 Views Asked by At

I am trying to make a controlled multiselect (multiselect-react-dropdown) using react-hook-form.

My problem is when I submit the form and use reset from useForm to clear the form, the selected values from before do not get added to the list as part of reset, only when I choose another option it will refresh the dropdown list and add the previous selected values:

Codebox

Steps to reproduce: choose some options, press submit, open dropdown to see previous selected options missing.

Expected: previous selected options return to the dropdown right away on reset

1

There are 1 best solutions below

0
Prashant Jangam On

You need to use resetSelectedValues using ref as mentioned on https://www.npmjs.com/package/multiselect-react-dropdown

import Multiselect from "multiselect-react-dropdown";
import { Controller, FieldValues, useForm } from "react-hook-form";
import React from "react";

const App = () => {
  const {
    handleSubmit,
    control,
    reset,
    formState: { isValid }
  } = useForm();

  const categories = [
    { id: 0, name: "abc" },
    { id: 1, name: "def" },
    { id: 2, name: "ghi" },
    { id: 3, name: "jkl" }
  ];

  const ref = React.useRef<any>();

  const onSubmit = (article: FieldValues) => {
    reset();
    if (ref.current) {
      ref.current?.resetSelectedValues();
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        control={control}
        name="categories"
        render={({ field: { value, onChange } }) => (
          <Multiselect
            options={categories.map(
              (category) => category.id + " - " + category.name
            )}
            isObject={false}
            avoidHighlightFirstOption={true}
            onSelect={onChange}
            onRemove={onChange}
            selectedValues={value}
            ref={ref}
          />
        )}
      />

      <div>
        <input
          disabled={!isValid}
          className="btn btn-dark"
          type="submit"
          value={"Submit"}
        />
      </div>
    </form>
  );
};

export default App;