Formik build forms in React Native

Formik – build forms in React Native

Ina HranovaIna Hranova 2 minutes 160 views

Share:

Formik comes with battle-tested solutions for input validation, formatting, masking, arrays, and error handling. This means you spend less time writing form code and more time building your next big thing. For example, we’re going to learn to build a basic newsletter using Formik.

Installation

To get started, Formik can be easily installed with both yarn and npm

npm install formik --save

or

yarn add formik

Next, we can start creating our form. Firstly, it can then be imported easily using

import React from "react";
import { useFormik } from "formik";

To create a simple form for newsletter, we can write:

const SignupForm = () => {
// Pass the useFormik() hook initial form values
// be called when the form is submitted
const formik = useFormik({
    initialValues: {
    email: "",
},
onSubmit: (values) => {
    alert(JSON.stringify(values, null, 2));
},
});
return (
    <form onSubmit={formik.handleSubmit}>
       <label htmlFor="email">Email Address</label>
       <input id="email" name="email" type="email" 
              onChange={formik.handleChange} value={formik.values.email} />
      <button type="submit">Submit</button>
    </form>
);};

Formik is an easy to use library that lets us add forms to a React with form validation without the hassle of handling form values ourselves.

Also, it will return form validation errors automatically so that we don’t have to deal with them ourselves.

 

Feel free to check out Formik documentation.

Happy coding! 🚀