Search code examples
reactjsformikuse-effectformik-material-ui

Formik Field Depending on Two Others


I created a codesandbox that shows 3 formik fields: first name, last name, and name.

I'm trying to make the field name display ${firstName} ${lastName} only until the user modifies the name field themselves, and so the condition name === firstName + ' ' + lastName fails, after which the name field should not be automatically updated anymore.

The challenge is that I'm trying to make this code live in the MyContactForm.tsx file since I need to be reusing that logic of inter-field dependency in other similar My*Form.tsx components thereafter, and therefore reuse the "generic" MyForm.tsx component without change.


Solution

  • Did a couple of changes so that your usage of MyContactForm is unchanged.

    1. Added an optional prop onChange: (nextValue: string) => void to MyTextField so that this will be called when the field value is changed
    2. Added our custom logic in the above-defined callback so that the previous form logic is extended not over-ridden.
    3. Added a follow field in the form inside the MyCustomForm to decide whether to track the changes from firstName and lastName or not. (Check the chat for the pseudo code)
    4. Destructed the follow prop when calling the form submission callback from App.tsx such the developer only receives only those form values that he/she is expecting/seeing from MyContactForm

    enter image description here

    This is the forked sandbox which contains the solution.