Home > Mobile >  How to set default value in multiselect dropdown in multistep form with react-select
How to set default value in multiselect dropdown in multistep form with react-select

Time:07-07

I am currently working on a multistep form with multiselect dropdowns with react-select. Everything works so far, except when switching between steps, the dropdown fields are not filled with the values of the current state.

// CreateForm.js

function CreateForm() {
  const [selectedValue, setSelectedValue] = useState({
    profile_name: "",
    car: "",
  });

  const [step, setStep] = useState(1);

  const nextStep = () => {
    if (step < 2) {
      setStep(step   1);
    } else if (step === 2) {
      console.log(selectedValue);
    }
  };

  const prevStep = () => {
    if (step > 1) {
      setStep(step - 1);
    }
  };

  const handleChange = (name) => (e) => {
    setSelectedValue((prevState) => ({
      ...prevState,
      [name]: Array.isArray(e) ? e.map((x) => x.value) : [],
    }));
    console.log(selectedValue);
  };

  return (
    <div className="bg-dark vh-100 text-light">
      <div className="d-flex flex-column justify-content-center">
        <div>
          {
            {
              1: (
                <CreateFormFirstStep
                  handleChange={handleChange}
                  optionSelected={selectedValue}
                />
              ),
              2: (
                <CreateFormSecondStep
                  handleChange={handleChange}
                />
              ),
            }[step]
          }
        </div>
      </div>
      <div className="d-flex flex-row justify-content-around px-5 mt-5">
        {step > 1 ? (
          <button className="btn btn-secondary" onClick={prevStep}>
            Back
          </button>
        ) : null}
        <button className="btn btn-primary" onClick={nextStep}>
          {step === 2 ? "Save" : "Next"}
        </button>
      </div>
    </div>
  );
}

export default CreateForm;

// CreateFormFirstStep

const CreateFormFirstStep = ({ handleChange }, selectedValue ) => {
  const data = [
  { value: 'bugatti', label: 'Bugatti' },
  { value: 'ferrari', label: 'Ferrari' },
  { value: 'am', label: 'Aston Martin' },
  { value: 'koenigsegg', label: 'Koenigsegg' },
  { value: 'bmw', label: 'BMW' },
  { value: 'cadillac', label: 'Cadillac' },
];
  return (
    <div className="CreateFormFirstStep">
      <h3>Test name</h3>
            <Select
              className="text-dark"
              style={{ display: "flex", flexDirection: "column" }}
              placeholder="Choose..."
              options={data}
              isMulti
              closeMenuOnSelect={false}
              hideSelectedOptions={false}
              isLoading={!data}
              onChange={handleChange("car")}
              defaultValue={selectedValue.car}
              selectedValue={selectedValue.car}
              name={"car"}
            />
    </div>
  );
};

export default CreateFormFirstStep;

So when switching between the two steps in the form, the chosen values are not preset in the select field. However as seen in the console, the state is saved correctly. How do I fill the Select field with the current state values when switching between steps? Help is very much appreciated.

CodePudding user response:

I found the error in the handleChange function. It should save the state as an object with value and label instead of an array:

  const handleChange = (name) => (e) => {
    setSelectedValue((prevState) => ({
      ...prevState,
      [name]: e.map((x) => ({
        value: x.value,
        label: x.label,
      })),
    }));
    console.log(selectedValue);
  };
  • Related