Easy Form Control in React

Dean McCafferty
2 min readJan 23, 2021

--

Photo by Florian Olivo on Unsplash

Forms in React can be very simple at first to grasp.

For example, a simple log on form can be simple to implement. Take a look at the sample code below.

This is a simple form with two inputs surrounded by a form. Click the button and the form will submit, calling the handleSubmit function. From this function the username and password can be sent to a backend for validation, etc.

But what happens when a form gets big? Like creating a form for a user to apply for a loan, when you need to process a lot of data. It can become a headache.

This is where Formik comes in. Formik takes care of the painful things when building a large, complex form. It helps keep track of state, errors and even validation (integrates with Yup validation very well!).

In comes Formik…

Formik is a lightweight library that helps take the pain away from form creation. There are other tools that can accomplish this task also but these can negatively affect performance and hide a lot of the “magic” of what they are doing.

Install Formik by simply using NPM or Yarn.

npm install formik --save

or

yarn add formik

Formik can be used as would normally, by wrapping a component in Formik, but I preferred using Formiks Higher Order Component. Take a look at the example below:

This example shows a much cleaner and expandable solution. State management is handled by Formiks handleChange function. This will use the id of the input field its attached to and automatically assign the value to the values variable.

The handleSubmit function is called when the form is submitted, from here you can call any function you passed into your component by using the formikBag props.

There are many props that Formik provides. Things that cover validation, handling dirty data, etc. Full API documentation can be found on Formiks website.

Conclusion

Building a form in React doesn’t have to be a headache, simple forms can be handled in the traditional way using a form and handling your state. As more complex forms start to grow it is wise to implement Formik to do a lot of the heavy lifting, making developing a form much more pain free.

--

--

Dean McCafferty

Software engineer with experience in React, Node, C/C++, Java, SOLID principles, and well designed code