Reputation: 63
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
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
- 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");
};
- I changed
value
prop inSelect
field. so that correct value can be passed to the function. because you are passingname
insetFieldValue
function.
value={defaultValue(options, values.name)}
working example https://codesandbox.io/s/agitated-clarke-4pjdy
Upvotes: 2