net - UK (2020-01)

(Antfer) #1

PROJECTS
Formik


FORMIK


options. If everything is fine, the form will submit
but, if not, the user receives an error message.
To start, open the ‘tutorial’ directory from the
tutorial files on the command line. Install the
dependencies and start the server. This app is built
upon create-react-app and includes its packages, along
with Formik itself and a couple of others to help
with styling.

> npm install
> npm start

The development server will start and the
application then opens in the browser. The App.js
file controls the whole application that will render
our container component for the form. Open up src/
App.js and import the <VoteContainer> component.

import VoteContainer from “./VoteContainer”;

MANAGE REACT FORM


STATE WITH FORMIK


Matt Crouch shows how one tool can help take the pain out of handling


the validation and submission of React-powered forms


Form elements hold their values in their own
internal state – at odds with React’s state-
driven approach. To make the two work together, we
need a more involved solution, such as using
controlled components for each field.
But there are many more aspects to creating a
form than just capturing data. We need to check the
formatting is correct, all required fields have been
set and that everything was sent successfully when
submitted. That leads to a lot of complicated logic
that can build up fast.
Formik is a lightweight library that handles these
problems. By wrapping a form with the supplied
components, we get a lot of this behaviour for free.
All we need to supply is the code to handle what
makes our form unique.
To help us explore what Formik can do, we will
be building a small voting application. The user can
enter their name and vote on one of the supplied

ABOUT THE AUTHOR
MATT CROUCH
w: mattcrouch.net
t: @mattcrouchuk
job: Software engineer at
Vidsy
areas of expertise:
React, accessibility and
styled components

View source


files here!
All the files you need for
this tutorial can be found at
https://github.com/MattCrouch/
formik-tutorial
Free download pdf