Juan_mejia
Juan_mejia

Reputation: 63

Set field value with formik to react-select component from external button

I have a formik form that containa react-select field so My issue is that i have another fields and buttons that can affect the default value of the react-select component, I tried to use the setFieldValue function form formik but this indeed change the form value but the option in the select is not displayed

here de codeSandbox I did with a simple example of what I'm tryng to do

Any idea about this

Upvotes: 0

Views: 5838

Answers (1)

harish kumar
harish kumar

Reputation: 1759

As far as I understand, On clicking the Add option button, a new option should be added in the options list and that option will also be marked as selected.

For that, I did the following changes

  1. Created the options list as useState hook so that we can alter list accordingly
 const [options, setOptions] = useState([
    { value: "options 1", label: "option 1" },
    { value: "options 2", label: "option 2" }
  ]);

and call setOptions in handleAddOption function.

 const handleAddOption = () => {
    setOptions([...options, { label: "test option", value: "test option" }]);
    return setFieldValue("name", "test option");
  };
  1. I changed value prop in Select field. so that correct value can be passed to the function. because you are passing name in setFieldValue function.
 value={defaultValue(options, values.name)} 

working example https://codesandbox.io/s/agitated-clarke-4pjdy

Upvotes: 2

Related Questions