Advanced Formik Techniques: Maximizing Current Form Value Accessibility

Advanced Formik Techniques: Maximizing Current Form Value Accessibility

Handling forms in React can be complex, especially when working with multi-paged forms, and forms with different input types like text, checkboxes, dropdowns, etc. Certainly, state management tools like useReducer and redux help in state management. However, they can be complex to implement. This is where libraries like Formik come in.

Formik is an excellent form library for React that simplifies form management by providing a wide range of features such as form state management, validation, and handling form submissions.

In addition to its core functionality, Formik offers a straightforward way to access the current values of a form without triggering a form submission.

This article will guide you through the process of retrieving the current form values using Formik and provide code examples to illustrate the implementation.

Why Formik is Great:

Before delving into accessing form values, let's explore why Formik is a popular choice for form management in React applications.

  1. Declarative Approach:

    Formik allows you to define your form's behavior in a declarative manner by leveraging React components. You can easily specify form fields, validation rules, and submission handling using JSX syntax, resulting in cleaner and more maintainable code.

  2. Form State Management:

    Formik simplifies the management of the form state by handling input values, validation errors, and form submission status out of the box. It provides a consistent API for accessing and updating form states, which significantly reduces the boilerplate code required to handle complex forms.

  3. Powerful Validation Support:

    Validating form input is a crucial aspect of any form implementation. Formik offers robust validation capabilities, allowing you to define validation rules, perform asynchronous validations, and display validation errors to users.

    It seamlessly integrates with popular validation libraries like Yup, making it easy to handle complex validation scenarios with lesser lines of code.

  4. Form Submission Handling:

    Formik ensures that handling form submissions is more straightforward. It provides an intuitive API for submitting forms, including support for asynchronous form submissions and handling submission status, errors, and success messages.

  5. Integration with React Ecosystem:

    Formik plays well with other React libraries and frameworks. It seamlessly integrates with popular UI libraries such as Material-UI, Mantine UI, Chakra UI, and Bootstrap, providing a cohesive experience for building forms with pre-built components. Additionally, Formik supports React hooks, allowing you to leverage the benefits of hooks in your form implementation.

Accessing Current Form Values with Formik:

Now, let's focus on retrieving the current form values without triggering a form submission using Formik. Follow the steps below to implement this functionality:

  1. Install Formik: Begin by installing Formik in your project by running npm install formik.

  2. Set Up a Form with Formik: Define your form structure using Formik's Form component and include form fields using the Field component. Specify the form's initial values using the initialValues prop, which can be an object with key-value pairs representing the form fields.

  3. Accessing Current Form Values: To access the current form values, you can utilize the useFormikContext hook provided by Formik. This hook allows you to access the Formik context, including the current form values. Here's an example code snippet:

import React from 'react';
import { useFormik, useFormikContext } from 'formik';

const MyForm = () => {
  const formik = useFormik({
    initialValues: {
      name: '',
      email: '',
    },
    // Other Formik configuration options
  });

  const handleInputChange = (e) => {
    formik.handleChange(e); // Update form values

    // Access the current form values
    const { values } = useFormikContext();
    console.log(values);
  };

  return (
    <form onSubmit={formik.handleSubmit}>
      <input
        type="text"
        name="name"
        value={formik.values.name}
        onChange={handleInputChange}
      />
      <input
        type="email"
        name="email"
        value={formik.values.email}


        onChange={handleInputChange}
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default MyForm;

In the code snippet above, the Formik's useFormik hook is used to define a form. Inside the handleInputChange function, we update the form values using formik.handleChange. We then use the useFormikContext hook to access the current form values, which are logged to the console for demonstration purposes.

Accessing current form values in different components

If you need to access the current form values from a different component than the one where the form is located, you can achieve this by utilizing Formik's FormikProvider and the useFormikContext hook. This approach allows you to share the form state across components.

Let's assume you have a form component called MyForm and a separate component called DisplayFormValues that needs asccess to the current form values. Here's how you can implement it:

MyForm.jsx:

import React from 'react';
import { Formik, Form, Field, useFormikContext, FormikProvider } from 'formik';

const MyForm = () => {
  return (
    <Formik
      initialValues={{
        name: '',
        email: '',
      }}
      onSubmit={(values) => {
        // Handle form submission
        console.log(values);
      }}
    >
      <Form>
        <Field type="text" name="name" />
        <Field type="email" name="email" />
        <button type="submit">Submit</button>
      </Form>
    </Formik>
  );
};

export default MyForm;

DisplayFormValues.jsx:

import React from 'react';
import { useFormikContext } from 'formik';

const DisplayFormValues = () => {
  const { values } = useFormikContext();

  return (
    <div>
      <h2>Current Form Values</h2>
      <p>Name: {values.name}</p>
      <p>Email: {values.email}</p>
    </div>
  );
};

export default DisplayFormValues;

App.jsx:

import React from 'react';
import MyForm from './MyForm';
import DisplayFormValues from './DisplayFormValues';

const App = () => {
  return (
    <div>
      <FormikProvider>
        <MyForm />
        <DisplayFormValues />
      </FormikProvider>
    </div>
  );
};

export default App;

In the above example, we wrap both the MyForm and DisplayFormValues components with the FormikProvider. The FormikProvider component ensures that both components have access to the same Formik context.

Inside the DisplayFormValues component, we use the useFormikContext hook to access the values object, which contains the current form values. We can then display these values in the component.

By using the FormikProvider and useFormikContext, we establish a connection between the form component and the component that needs to access the form values.

This way, you can access the current form values from a different component without the form being present in the same component hierarchy.

Remember to import the necessary modules from the formik library in all relevant files.

This implementation allows you to share form values and access them in separate components, enabling you to display the form values or perform any required operations in real-time without the need for the form to be on the same component.

Conclusion

Formik provides an excellent solution for form management in React applications, offering a wide range of features and a declarative API. When Formik's useFormikContext hook is leveraged, you can access the current form values without triggering a form submission.

This enables you to perform real-time operations, validate form fields dynamically, or create interactive form experiences. With Formik, managing forms in React becomes more intuitive and efficient, enhancing the overall development experience.