Skip to content

Instantly share code, notes, and snippets.

@jsmolina
Last active June 2, 2023 13:08
Show Gist options
  • Save jsmolina/37c7f9aa20733dbdeebb2a53f1dfd264 to your computer and use it in GitHub Desktop.
Save jsmolina/37c7f9aa20733dbdeebb2a53f1dfd264 to your computer and use it in GitHub Desktop.
Working with a dynamic array of multiple Fields in React Formik (very basic example)
export const TextField = ({name}) => {
const { touched, values, errors, handleBlur, handleChange } = useFormikContext();
const isTouched = getIn(touched, name);
const value = getIn(values, name);
const error = getIn(errors, name);
// getIn automates for you getting values["text"][0]
const isTouched = getIn(touched, name);
const value = getIn(values, name);
const error = getIn(errors, name);
return <div><input name={name} type="text" value={value} /><div>{error}</div></div>;
};
export const TextFieldsList = () => {
// just name every field with field.index
return (
<>
<TextField name="text.0" />
<TextField name="text.1" />
</>
);
};
const validation = useMemo(
() =>
Yup.object().shape({
text: Yup.array().of(
Yup.string().matches(IP_RANGE_REGEX, {
excludeEmptyString: true,
message: "invalid ip range format",
})
),
}),
[]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment