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 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