I have written code with react-select and Formik. I used useField()
for select component, but when I tried to change the default value, I got empty selected value.
const SelectField = ({ name, ...selectProps }) => {
const [field, meta, helpers] = useField(name)
return (
<Select
value={field.value}
onChange={(v) => helpers.setValue(v)}
onBlur={() => helpers.setTouched(true)}
{...selectProps}
/>
)
}
then this is my implementation for that component
<SelectField
name="category"
defaultValue={values.category.map((c) => {
console.log(c)
return {
value: c,
label: c,
}
})}
closeMenuOnSelect={false}
components={animatedComponents}
isMulti
options={categories.map((c) => {
return {
value: c.name,
label: c.name,
}
})}
/>
assume that values.category is some value from categories data.
change value of that select to field.defaultValue
const SelectField = ({ name, ...selectProps }) => {
const [field, meta, helpers] = useField(name)
return (
<Select
value={field.defaultValue}
onChange={(v) => helpers.setValue(v)}
onBlur={() => helpers.setTouched(true)}
{...selectProps}
/>
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.