Last active
June 2, 2023 13:08
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const TextFieldsList = () => { | |
// just name every field with field.index | |
return ( | |
<> | |
<TextField name="text.0" /> | |
<TextField name="text.1" /> | |
</> | |
); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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