4

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

2 Answers 2

8

Solution 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>
Sign up to request clarification or add additional context in comments.

Comments

0

For me below worked:

setFieldValue(`translations[${index}].name`, v.target.value)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.