Page Content

Tutorials

Understanding the Formik in React.js With Code Example

Formik in React.js

A third-party React.js form library called Formik provides fundamental form programming and validation features. Its foundation is the idea of regulated components, which drastically cuts down on the amount of time needed for form development.

Formik efficiently manages user interactions and the status of your forms. Formik in React.js offers an organised approach to handling the value and onChange events for each input element rather than managing them directly. This guarantees that the user interface displays the most recent state based on user interactions. Responding to user input and carrying out operations like data validation are made simpler as a result.

Formik in React.js
Formik in React.js

How to Use Formik

The usual steps to utilise Formik are as follows:

Setting up the Application and Installing Formik: Installing Formik and configuring the application You start by making a new React application, for instance with a Rollup bundler or Create React App. Once your simple React project is configured, you use npm to install the Formik library: Install formik with npm save.

Defining Initial Values: Establishing Starting Values All of the form fields’ initial values are defined either as a distinct object or in the constructor of your component. The initial state of your form is this item. For example, you may set the name, amount, date, and category fields on an expenditure form to be empty strings.

Validation: Verification You can specify a validation method in Formik in React.js that accepts the current form values as an argument. In the event that any validation criteria are broken, this method ought to produce an errors object. You can specify an error message for a field that is necessary but not provided. After that, Formik makes these mistakes visible to the render props of your form, enabling you to show the user validation messages.

Submission Handling: When the form is submitted, Formik in React.js will call the handleSubmit method you created. The setSubmitting function and the current form values are passed to this method. This method lets you show an alert, transmit data to an API, or visit another site. To control the form’s submission status, use the setSubmitting function to block and re-enable the submit button.

Rendering the Form with Formik Component: Form Rendering using Formik Wrapping form elements within the <Formik> component is the key to using Formik. This component connects your form’s logic and structure to Formik in React.js complex state management via initialValues, validate, and onSubmit. The <Formik> component utilises a render prop pattern to offer form elements with utility methods and state variables (e.g., values, errors, touched, handleChange, handleBlur, handleSubmit, is Submitting.

Code Example:

Let’s use an ExpenseForm component to demonstrate how to use Formik. Basic input fields for handling submissions, validation, and spending details will be included in this example.

import React, { useState } from 'react';
export default function ExpenseForm() {
  const [data, setData] = useState({ name: '', amount: '', date: '', category: '' });
  const [msg, setMsg] = useState('');
  const [err, setErr] = useState({});
  const handleChange = e => setData({ ...data, [e.target.name]: e.target.value });
  const handleSubmit = e => {
    e.preventDefault();
    const errs = {};
    Object.keys(data).forEach(k => { if (!data[k]) errs[k] = `{k} required`; });
    if (Object.keys(errs).length) return setErr(errs);
    setErr({});
    setTimeout(() => {
      setMsg(JSON.stringify(data, null, 2));
      setData({ name: '', amount: '', date: '', category: '' });
    }, 500);
  };
  return (
    <form onSubmit={handleSubmit} className="max-w-sm mx-auto mt-10 space-y-3 p-4 bg-white shadow rounded">
      {['name', 'amount', 'date'].map(f => (
        <div key={f}>
          <input name={f} type={f === 'date' ? 'date' : 'text'} value={data[f]} onChange={handleChange}
            placeholder={f} className="w-full border p-2 rounded" />
          {err[f] && <p className="text-red-500 text-sm">{err[f]}</p>}
        </div>
      ))}
      <select name="category" value={data.category} onChange={handleChange} className="w-full border p-2 rounded">
        <option value="">Select Category</option>
        <option>Food</option><option>Entertainment</option><option>Academic</option>
      </select>
      {err.category && <p className="text-red-500 text-sm">{err.category}</p>}
      <button type="submit" className="w-full bg-indigo-600 text-white p-2 rounded">Submit</button>
      {msg && <pre className="bg-green-100 p-2 text-sm">{msg}</pre>}
    </form>
  );
}

Output:

Add Expense
name
amount
dd-mm-yyyy
Select Category
Submit

Explanation of the Code

Imports: The code starts by importing the component’s CSS file as well as React and Formik from the corresponding libraries. The material’s commented-out examples of other imports, such as connect and withRouter, demonstrate how Formik in React.js components can be used with routing frameworks like React Router and state management libraries like Redux.

Constructor(props):This is initialised by the constructor.initialValues for name, amount, date, and category are empty strings. The form fields’ initial state is defined by these values.

Validate = (values):Form validation is handled by this arrow function. It checks to see if each necessary field has a value after receiving the values object, which contains the current state of every form field. It adds a “Required” error message to the errors object if a field is left unfilled. The function then returns this errors object. The render function will immediately have access to these faults with Formik.

HandleSubmit = (values, { setSubmitting }): Form submission triggers the handleSubmit = (values, { setSubmitting }) function. It gets a setSubmitting method and the form’s values. An asynchronous operation, such an API call to save expenditure data, is simulated in this example using a setTimeout.

Alert(JSON.stringify(values, null, 2)) shows the form data in a pop-up window following the simulated process, and setSubmitting(false) modifies Formik’s internal state to show that the submission is finished, reactivating the submit button. According to the a navigation action (this.props.history.push(“/list”) might be added here to reroute the user upon a successful submission if this component was connected with react-router-dom.

Render() Method: The complete form is wrapped by the <Formik> component. It requires the properties onSubmit, validate, and initialValues. The render prop function is contained within <Formik>. Formik in React.js provides this function with an object with a number of useful properties. All form fields’ current values. An object with messages about validation errors in it.

An object that keeps track of whether a user has “touched” or visited a field. By doing this, mistakes can be shown only after a user has worked with a field. As the user types or chooses options, the form’s values are updated via the handleChange generic event handler. When a user exits a field, handleBlur, a generic event handler, marks it as touched. handleSubmit Form submission function. Boolean indicating form submission.

  • Use normal HTML form elements (<label>, <input>, <select>, <button>) in the render prop function.
  • Input values depend on characteristics.To handle components, use fieldName (e.g., value={values.name}).
  • Formik in React.js handleChange and handleBlur routines respond to input element onChange and onBlur events.
  • Errors are used to conditionally display error messages.touched fieldName &&.mistakes && fieldName.fieldName. This guarantees that mistakes appear only after a user has worked with the field.
  • Multiple submissions are prevented while the form is processing because the disabled attribute of the submit button is tied to isSubmitting.

Once the program has been launched (for example, npm start) and opened in a web browser, you can input sample spending information and press “Submit.” Pop-up message boxes display submitted data. Finally, Formik in React.js manages validation, form state, and submissions to simplify React form building. Controlled components and the render prop pattern simplify complex form logic construction and maintenance.

Conclusion

In conclusion, Formik in React.js is a powerful and efficient form management library in React.js that significantly simplifies handling form state, validation, and submission. By abstracting away the repetitive tasks typically involved in form handling, such as managing field values, errors, and touched states, Formik in React.js promotes cleaner, more maintainable code. Its use of controlled components and render prop patterns ensures that form inputs always reflect the latest application state while providing developers with full control over behavior and appearance.

The structured approach provided by Formik in React.js allows for easy implementation of custom validation, real-time error feedback, and asynchronous submission logic, making it ideal for building scalable and user-friendly forms in modern React applications.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index