-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Description
Feature request
Current Behavior
Formik does not provide a built-in method to retrieve a field value dynamically by name, especially when dealing with nested fields. Currently, developers access values using values[fieldName], which works for flat structures but does not support dot notation for nested fields.
const value = values["user.email"]; // Undefined, does not work
console.log(value);
Desired Behavior
Formik should provide a built-in utility function that allows dynamic retrieval of field values using dot notation. This would make it easier to access deeply nested values without manually handling object traversal.
const value = formik.getFieldValue("user.email");
console.log(value); // Expected output: user's email value
Suggested Solution
A new utility function (e.g., getFieldValue) should be added to Formik, which:
- Accepts values and a fieldName string or only fieldName string (supporting dot notation).
- Traverses the object and returns the correct nested value.
function getFieldValue(values: Record<string, any>, fieldName: string) {
return fieldName.split('.').reduce((acc, key) => acc?.[key], values);
}
Who does this impact? Who is this for?
- All Formik users working with nested structures who need a consistent way to access deeply nested form values.
- Developers handling dynamic form fields, where field names are stored as strings and accessed programmatically.
- Users implementing reusable form components, especially in large applications where forms are dynamically generated.
- Teams working with TypeScript, since accessing nested fields directly can lead to type safety issues without proper validation.
Describe alternatives you've considered
- Using lodash.get(values, fieldName), which requires an additional dependency.
- Manually implementing a helper function in every project, which leads to code duplication.
Additional context
This feature would improve developer experience and make Formik more flexible for handling deeply nested forms. Adding this as a built-in utility will reduce redundant code and enhance usability.