TutorialsCourses
Course Menu
Formik for Beginners

Setting up Formik

Intro

If you were getting started on a normal project you'd want to add formik and yup by running yarn add formik yup or npm install formik yup. This already has them installed so just run yarn install or npm install to install the necessary dependencies. The project uses create-react-app which you may be familiar with.

Finally each lesson is a different branch. For lesson one you'll want to checkout lesson_01 branch by running git checkout lesson_01. If at any point you get stuck or are confused each lesson has a _end branch. So lesson_01_end is the final code that we'll be working towards.

Add Formik

We start by importing Formik. This will setup the context so everything rendered inside of Formik can access the context of this specific Formik form.

There are a few different ways to initiate a Formik form, but this is the easiest method to get started.

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

function App() {
  return (
    <div className="App">
      <Formik></Formik>
    </div>
  );
}

export default App;

Function Children

Now that we have it rendering Formik we need to supply our function as a child. This is where we will place all of our inputs that need access to this specific form context.

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

function App() {
  return (
    <div className="App">
      <Formik>
        {() => {
          return null;
        }}
      </Formik>
    </div>
  );
}

export default App;

Wire it Up

There are a few required props of Formik. The first is initialValues. This will setup all the default values for your fields. You aren't restricted to just the values supplied initially, but it does need to exist. Also you will need an onSubmit prop. This can either be synchronous or asynchronous. We won't focus on the onSubmit handler but in general it is most likely going to be asynchronous as you submit data to the server.

import React from "react";
import { Formik, Form } from "formik";

function App() {
  const handleSubmit = (values) => {};

  return (
    <div className="App">
      <Formik initialValues={{}} onSubmit={handleSubmit}>
        {() => {
          return <Form />;
        }}
      </Formik>
    </div>
  );
}

export default App;

The Form component is form wrapped. However it does have some added benefits. In a typical form in normal HTMl, when a form is submitted it will actually redirect you to the action url. This isn't what we want. So Form component from formik will capture the form submission, and call preventDefault for you. It will then trigger your onSubmit function.

In general it's best practice to wrap all of your content in Form.