CodexBloom - AI-Powered Q&A Platform

Formik v2: How to conditionally render fields based on another field's value without losing form state?

👀 Views: 0 💬 Answers: 1 📅 Created: 2025-06-20
react formik conditional-rendering

I'm using Formik v2 for handling forms in my React application, and I'm facing an issue where I need to conditionally render fields based on the value of another field. For instance, I have a dropdown for selecting a user type, and based on the type selected, I want to show additional fields for either 'Admin' or 'User'. The problem is, when I switch between these options, the previously entered data in the fields gets lost, which is not the intended behavior. Here's a simplified version of my code: ```javascript import React from 'react'; import { Formik, Form, Field } from 'formik'; const MyForm = () => { return ( <Formik initialValues={{ userType: '', adminField: '', userField: '' }} onSubmit={(values) => { console.log(values); }} > {({ values }) => ( <Form> <Field as="select" name="userType"> <option value="">Select User Type</option> <option value="admin">Admin</option> <option value="user">User</option> </Field> {values.userType === 'admin' && ( <Field name="adminField" placeholder="Admin Specific Field" /> )} {values.userType === 'user' && ( <Field name="userField" placeholder="User Specific Field" /> )} <button type="submit">Submit</button> </Form> )} </Formik> ); }; export default MyForm; ``` This code works for displaying the conditional fields, but when I change the selection from 'Admin' to 'User', the value in the 'adminField' gets cleared, and vice versa. I want to retain the values of these fields even when switching between them. I've tried using `setFieldTouched` and `setFieldValue`, but it seems I might be misunderstanding how Formik handles state for conditionally rendered fields. Any guidance on how to achieve this while keeping the form state intact would be greatly appreciated!