admin管理员组文章数量:1345179
We have a Formik form with translations. The initialValue looks like this:
{
// other stuff here like id, createdAt, etc.
translations: [
{
languageCode: 'de',
name: 'German',
},
{
languageCode: 'fr',
name: 'French',
},
{
languageCode: 'it',
name: 'Italian',
}
]
}
selectedLanguage
is equal to the currently selected language 'de' | 'fr' | 'it'.
Then we loop over the availableLanguages
and create and input field for each of it like so:
{
languages.map((lang, ind) => (
<div key={ind}>
{selectedLanguage === lang && (
<FormField>
<Input
name="Topic"
value={
values.translations?.find(
elm => elm.languageCode === lang
)?.name || ""
}
onChange={(v: React.ChangeEvent<HTMLInputElement>) => {
// Doesn't work
setFieldValue(
`${
values.translations?.find(
elm => elm.languageCode === lang
).name
}`,
v.target.value
);
}}
/>
</FormField>
)}
</div>
));
}
How do you dynamically set the name in the values array of the language that is being changed?
Thanks
We have a Formik form with translations. The initialValue looks like this:
{
// other stuff here like id, createdAt, etc.
translations: [
{
languageCode: 'de',
name: 'German',
},
{
languageCode: 'fr',
name: 'French',
},
{
languageCode: 'it',
name: 'Italian',
}
]
}
selectedLanguage
is equal to the currently selected language 'de' | 'fr' | 'it'.
Then we loop over the availableLanguages
and create and input field for each of it like so:
{
languages.map((lang, ind) => (
<div key={ind}>
{selectedLanguage === lang && (
<FormField>
<Input
name="Topic"
value={
values.translations?.find(
elm => elm.languageCode === lang
)?.name || ""
}
onChange={(v: React.ChangeEvent<HTMLInputElement>) => {
// Doesn't work
setFieldValue(
`${
values.translations?.find(
elm => elm.languageCode === lang
).name
}`,
v.target.value
);
}}
/>
</FormField>
)}
</div>
));
}
How do you dynamically set the name in the values array of the language that is being changed?
Thanks
Share Improve this question edited Dec 10, 2021 at 16:56 Amila Senadheera 13.3k16 gold badges29 silver badges46 bronze badges asked Dec 10, 2021 at 16:15 MichaMicha 2571 gold badge3 silver badges11 bronze badges2 Answers
Reset to default 8Solution was pretty simple:
<FormField key={index}>
<Input
value={(values.translations && values.translations[index].name) || ''}
onChange={(v: React.ChangeEvent<HTMLInputElement>) =>
setFieldValue(`translations.${index}.name`, v.target.value)
}
onBlur={() => setFieldTouched(`translations.${index}.name`, true)}
/>
</FormField>
For me below worked:
setFieldValue(`translations[${index}].name`, v.target.value)
本文标签: javascriptFormik setFieldValue of element in array dynamicallyStack Overflow
版权声明:本文标题:javascript - Formik setFieldValue of element in array dynamically - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743785903a2538679.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论