Full Code of jaredpalmer/formik for AI

main 91475adbf335 cached
250 files
1.4 MB
520.0k tokens
203 symbols
1 requests
Download .txt
Showing preview only (1,479K chars total). Download the full file or copy to clipboard to get everything.
Repository: jaredpalmer/formik
Branch: main
Commit: 91475adbf335
Files: 250
Total size: 1.4 MB

Directory structure:
gitextract_fwjymvec/

├── .all-contributorsrc
├── .changeset/
│   ├── README.md
│   └── config.json
├── .codesandbox/
│   └── ci.json
├── .eslintrc.js
├── .github/
│   ├── CODEOWNERS
│   ├── CODE_OF_CONDUCT.md
│   ├── CONTRIBUTING.md
│   ├── FUNDING.yml
│   ├── ISSUE_TEMPLATE/
│   │   ├── 1.Bug-report.md
│   │   ├── 2.Feature-request.md
│   │   └── config.yml
│   └── workflows/
│       ├── ci.yml
│       ├── release.yml
│       └── stale.yml
├── .gitignore
├── .kodiak.toml
├── .nvmrc
├── .prettierrc
├── .vscode/
│   └── settings.json
├── LICENSE
├── SECURITY.md
├── app/
│   ├── .gitignore
│   ├── README.md
│   ├── next-env.d.ts
│   ├── package.json
│   ├── pages/
│   │   ├── _app.js
│   │   ├── basic.js
│   │   ├── index.tsx
│   │   └── sign-in.js
│   ├── styles/
│   │   └── globals.css
│   └── tsconfig.json
├── docs/
│   ├── 3rd-party-bindings.md
│   ├── api/
│   │   ├── connect.md
│   │   ├── errormessage.md
│   │   ├── fastfield.md
│   │   ├── field.md
│   │   ├── fieldarray.md
│   │   ├── form.md
│   │   ├── formik.md
│   │   ├── useField.md
│   │   ├── useFormik.md
│   │   ├── useFormikContext.md
│   │   ├── utils.md
│   │   └── withFormik.md
│   ├── examples/
│   │   ├── async-submission.md
│   │   ├── basic.md
│   │   ├── checkboxes.md
│   │   ├── dependent-fields-async-api-request.md
│   │   ├── dependent-fields.md
│   │   ├── field-arrays.md
│   │   ├── instant-feedback.md
│   │   ├── more-examples.md
│   │   ├── radio-group.md
│   │   ├── typescript.md
│   │   └── with-material-ui.md
│   ├── examples.md
│   ├── guides/
│   │   ├── arrays.md
│   │   ├── form-submission.md
│   │   ├── react-native.md
│   │   ├── typescript.md
│   │   └── validation.md
│   ├── manifest.json
│   ├── migrating-v2.md
│   ├── overview.md
│   ├── resources.md
│   └── tutorial.md
├── e2e/
│   └── basic.test.ts
├── examples/
│   ├── AsyncValidation.js
│   ├── CombinedValidations.js
│   ├── CustomInputs.js
│   ├── DebouncedAutoSave.js
│   ├── Debug.js
│   ├── ErrorMessage.js
│   ├── FastField.js
│   ├── MultistepWizard.js
│   ├── RoutedMultistepWizard.js
│   ├── RoutedMultistepWizard2.js
│   ├── SchemaValidation.js
│   ├── SyncValidation.js
│   ├── ValidateFieldWithSchema.js
│   ├── async-submission/
│   │   ├── README.md
│   │   ├── index.js
│   │   └── package.json
│   ├── basic/
│   │   ├── README.md
│   │   ├── index.js
│   │   └── package.json
│   ├── basic-typescript/
│   │   ├── README.md
│   │   ├── index.html
│   │   ├── index.tsx
│   │   ├── package.json
│   │   └── tsconfig.json
│   ├── checkboxes/
│   │   ├── README.md
│   │   ├── index.js
│   │   └── package.json
│   ├── dependent-fields/
│   │   ├── README.md
│   │   ├── index.js
│   │   ├── package.json
│   │   └── styles.css
│   ├── dependent-fields-async-api-request/
│   │   ├── README.md
│   │   ├── index.js
│   │   ├── package.json
│   │   └── styles.css
│   ├── field-arrays/
│   │   ├── README.md
│   │   ├── index.js
│   │   └── package.json
│   ├── field-level-validation/
│   │   ├── README.md
│   │   ├── index.js
│   │   └── package.json
│   ├── instant-feedback/
│   │   ├── README.md
│   │   ├── index.js
│   │   ├── package.json
│   │   └── styles.css
│   ├── radio-group/
│   │   ├── README.md
│   │   ├── index.js
│   │   └── package.json
│   ├── with-material-ui/
│   │   ├── README.md
│   │   ├── index.js
│   │   └── package.json
│   └── withFormik.js
├── package.json
├── packages/
│   ├── formik/
│   │   ├── .gitignore
│   │   ├── CHANGELOG.md
│   │   ├── MIGRATING-v2.md
│   │   ├── README.md
│   │   ├── package.json
│   │   ├── src/
│   │   │   ├── ErrorMessage.tsx
│   │   │   ├── FastField.tsx
│   │   │   ├── Field.tsx
│   │   │   ├── FieldArray.tsx
│   │   │   ├── Form.tsx
│   │   │   ├── Formik.tsx
│   │   │   ├── FormikContext.tsx
│   │   │   ├── connect.tsx
│   │   │   ├── index.tsx
│   │   │   ├── types.tsx
│   │   │   ├── utils.ts
│   │   │   └── withFormik.tsx
│   │   ├── test/
│   │   │   ├── ErrorMessage.test.tsx
│   │   │   ├── Field.test.tsx
│   │   │   ├── FieldArray.test.tsx
│   │   │   ├── Formik.test.tsx
│   │   │   ├── setupTests.ts
│   │   │   ├── testHelpers.ts
│   │   │   ├── tsconfig.json
│   │   │   ├── types.test.tsx
│   │   │   ├── utils.test.tsx
│   │   │   ├── withFormik.test.tsx
│   │   │   └── yupHelpers.test.ts
│   │   ├── tsconfig.build.json
│   │   └── types/
│   │       ├── global.d.ts
│   │       └── index.d.ts
│   └── formik-native/
│       ├── .gitignore
│       ├── CHANGELOG.md
│       ├── CONTRIBUTING.md
│       ├── README.md
│       ├── package.json
│       ├── src/
│       │   └── index.ts
│       ├── test/
│       │   └── blah.test.ts
│       └── tsconfig.build.json
├── playwright.config.ts
├── scripts/
│   ├── benchmark.tsx
│   ├── btag.sh
│   └── retag.sh
├── tsconfig.base.json
├── tsconfig.json
├── turbo.json
├── website/
│   ├── .eslintignore
│   ├── .eslintrc
│   ├── .gitignore
│   ├── .prettierignore
│   ├── README.md
│   ├── next-env.d.ts
│   ├── next.config.js
│   ├── package.json
│   ├── postcss.config.js
│   ├── public/
│   │   └── robots.txt
│   ├── scripts/
│   │   └── build-sitemap.js
│   ├── src/
│   │   ├── blog/
│   │   │   ├── formik-3-alpha.md
│   │   │   └── new-docs.md
│   │   ├── components/
│   │   │   ├── ArrowRight.tsx
│   │   │   ├── Banner.tsx
│   │   │   ├── Container.tsx
│   │   │   ├── DocsPageFooter.tsx
│   │   │   ├── ExternalLink.tsx
│   │   │   ├── Footer.tsx
│   │   │   ├── FormiumLogo.tsx
│   │   │   ├── Highlight2.tsx
│   │   │   ├── LayoutDocs.tsx
│   │   │   ├── Logo.tsx
│   │   │   ├── MDXComponents.tsx
│   │   │   ├── Nav.tsx
│   │   │   ├── ReactionForm.tsx
│   │   │   ├── Search.tsx
│   │   │   ├── Seo.tsx
│   │   │   ├── Sidebar.tsx
│   │   │   ├── SidebarCategory.tsx
│   │   │   ├── SidebarHeading.tsx
│   │   │   ├── SidebarMobile.tsx
│   │   │   ├── SidebarNavLink.tsx
│   │   │   ├── SidebarPost.tsx
│   │   │   ├── Sticky.tsx
│   │   │   ├── TWButton.tsx
│   │   │   ├── Toc.module.css
│   │   │   ├── Toc.tsx
│   │   │   ├── addRouterEvents.tsx
│   │   │   ├── clients/
│   │   │   │   ├── Client.tsx
│   │   │   │   ├── ClientsMarquee.tsx
│   │   │   │   └── Filters.tsx
│   │   │   ├── forwardRefWithAs.tsx
│   │   │   ├── markdown.module.css
│   │   │   ├── useBoolean.tsx
│   │   │   ├── useClipboard.tsx
│   │   │   ├── useIsMobile.tsx
│   │   │   ├── useOverScroll.tsx
│   │   │   ├── useTocHighlight.tsx
│   │   │   └── utils/
│   │   │       └── throttle.ts
│   │   ├── index.d.ts
│   │   ├── lib/
│   │   │   ├── blog/
│   │   │   │   └── mdxUtils.ts
│   │   │   ├── docs/
│   │   │   │   ├── config.ts
│   │   │   │   ├── findRouteByPath.tsx
│   │   │   │   ├── md-loader.js
│   │   │   │   ├── page.tsx
│   │   │   │   ├── rehype-docs.js
│   │   │   │   ├── remark-paragraph-alerts.js
│   │   │   │   ├── remark-plugins.js
│   │   │   │   └── utils.ts
│   │   │   ├── fs-utils.tsx
│   │   │   ├── get-route-context.tsx
│   │   │   ├── github/
│   │   │   │   ├── api.tsx
│   │   │   │   ├── constants.tsx
│   │   │   │   └── raw.tsx
│   │   │   └── types.tsx
│   │   ├── manifests/
│   │   │   ├── getManifest.ts
│   │   │   ├── manifest-1.3.0.json
│   │   │   ├── manifest-2.1.4.json
│   │   │   └── manifest.json
│   │   ├── pages/
│   │   │   ├── _app.js
│   │   │   ├── _document.js
│   │   │   ├── blog/
│   │   │   │   ├── [slug].tsx
│   │   │   │   └── index.tsx
│   │   │   ├── docs/
│   │   │   │   └── [...slug].tsx
│   │   │   ├── index.tsx
│   │   │   └── users.tsx
│   │   ├── siteConfig.tsx
│   │   ├── styles/
│   │   │   └── index.css
│   │   └── users.ts
│   ├── tailwind.config.js
│   └── tsconfig.json
└── yarn.lock

================================================
FILE CONTENTS
================================================

================================================
FILE: .all-contributorsrc
================================================
{
  "projectName": "formik",
  "projectOwner": "jaredpalmer",
  "files": [
    "packages/formik/README.md"
  ],
  "imageSize": 100,
  "commit": true,
  "contributors": [
    {
      "login": "jaredpalmer",
      "name": "Jared Palmer",
      "avatar_url": "https://avatars2.githubusercontent.com/u/4060187?v=4",
      "profile": "http://jaredpalmer.com",
      "contributions": [
        "question",
        "code",
        "design",
        "doc",
        "example",
        "ideas",
        "review",
        "test"
      ]
    },
    {
      "login": "eonwhite",
      "name": "Ian White",
      "avatar_url": "https://avatars0.githubusercontent.com/u/109324?v=4",
      "profile": "https://www.stardog.io",
      "contributions": [
        "question",
        "bug",
        "code",
        "doc",
        "ideas",
        "review"
      ]
    },
    {
      "login": "Andreyco",
      "name": "Andrej Badin",
      "avatar_url": "https://avatars0.githubusercontent.com/u/829963?v=4",
      "profile": "http://andrejbadin.com",
      "contributions": [
        "question",
        "bug",
        "doc"
      ]
    },
    {
      "login": "skattyadz",
      "name": "Adam Howard",
      "avatar_url": "https://avatars2.githubusercontent.com/u/91115?v=4",
      "profile": "http://adz.co.de",
      "contributions": [
        "question",
        "bug",
        "ideas",
        "review"
      ]
    },
    {
      "login": "VladShcherbin",
      "name": "Vlad Shcherbin",
      "avatar_url": "https://avatars1.githubusercontent.com/u/6711845?v=4",
      "profile": "https://github.com/VladShcherbin",
      "contributions": [
        "question",
        "bug",
        "ideas"
      ]
    },
    {
      "login": "brikou",
      "name": "Brikou CARRE",
      "avatar_url": "https://avatars3.githubusercontent.com/u/383212?v=4",
      "profile": "https://github.com/brikou",
      "contributions": [
        "bug",
        "doc"
      ]
    },
    {
      "login": "skvale",
      "name": "Sam Kvale",
      "avatar_url": "https://avatars0.githubusercontent.com/u/5314713?v=4",
      "profile": "http://skvale.github.io",
      "contributions": [
        "bug",
        "code",
        "test"
      ]
    },
    {
      "login": "jontansey",
      "name": "Jon Tansey",
      "avatar_url": "https://avatars0.githubusercontent.com/u/13765558?v=4",
      "profile": "http://jon.tansey.info",
      "contributions": [
        "bug",
        "code"
      ]
    },
    {
      "login": "slightlytyler",
      "name": "Tyler Martinez",
      "avatar_url": "https://avatars0.githubusercontent.com/u/6819171?v=4",
      "profile": "http://slightlytyler.com",
      "contributions": [
        "bug",
        "doc"
      ]
    },
    {
      "login": "MrLoh",
      "name": "Tobias Lohse",
      "avatar_url": "https://avatars0.githubusercontent.com/u/1285032?v=4",
      "profile": "http://MrLoh.se",
      "contributions": [
        "bug",
        "code"
      ]
    },
    {
      "login": "quantizor",
      "name": "Evan Jacobs",
      "avatar_url": "https://avatars.githubusercontent.com/u/570070?v=4",
      "profile": "https://quantizor.dev",
      "contributions": [
        "question",
        "code",
        "design",
        "doc",
        "example",
        "ideas",
        "review",
        "test"
      ]
    }
  ],
  "repoType": "github"
}


================================================
FILE: .changeset/README.md
================================================
# Changesets

Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it [in our repository](https://github.com/changesets/changesets)

We have a quick list of common questions to get you started engaging with this project in
[our documentation](https://github.com/changesets/changesets/blob/master/docs/common-questions.md)


================================================
FILE: .changeset/config.json
================================================
{
  "$schema": "https://unpkg.com/@changesets/config@1.3.0/schema.json",
  "changelog": ["@changesets/changelog-github", { "repo": "formium/formik" }],
  "commit": false,
  "linked": [],
  "access": "public",
  "baseBranch": "main",
  "updateInternalDependencies": "patch",
  "ignore": []
}


================================================
FILE: .codesandbox/ci.json
================================================
{
  "buildCommand": "build:codesandbox",
  "node": "18",
  "packages": ["packages/formik", "packages/formik-native"],
  "sandboxes": ["n4sgkx"]
}


================================================
FILE: .eslintrc.js
================================================
module.exports = {
  extends: [
    'react-app',
    'prettier/@typescript-eslint',
    'plugin:prettier/recommended',
  ],
  settings: {
    react: {
      version: 'detect',
    },
  },
};


================================================
FILE: .github/CODEOWNERS
================================================
# Learn how to add code owners here:
# https://help.github.com/en/articles/about-code-owners

*          @jaredpalmer @quantizor
/docs/     @jaredpalmer @quantizor
/examples/ @jaredpalmer @quantizor

================================================
FILE: .github/CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at jared@palmer.net. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]

[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/


================================================
FILE: .github/CONTRIBUTING.md
================================================
# Contributing to Formik

<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->

**Table of Contents**

- [Code of Conduct](#code-of-conduct)
- [Ways to Contribute](#ways-to-contribute)
- [Working on your first Pull Request?](#working-on-your-first-pull-request)
- [Sending a Pull Request](#sending-a-pull-request)
- [Working locally](#working-locally)
  - [Develop](#develop)
  - [Test](#test)
- [How to increase the chance of a change being accepted?](#how-to-increase-the-chance-of-a-change-being-accepted)
- [Working locally](#working-locally-1)
  - [Watching / Building packages](#watching--building-packages)
  - [Unit testing](#unit-testing)
  - [Playground / Integration testing](#playground--integration-testing)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

## Code of Conduct

Formik has adopted the [Contributor Covenant](https://www.contributor-covenant.org/) as its Code of Conduct, and we expect project participants to adhere to it.
Please read [the full text](/CODE_OF_CONDUCT.md) so that you can understand what actions will and will not be tolerated.

## Ways to Contribute

There are many ways to contribute to Formik, code contribution is one aspect of it.

- **Spread the word** - Evangelize Formik by linking to https://formik.org on your website, every backlink matters. Follow us on [Twitter](https://twitter.com/formiumhq), like and retweet the important news. Or just talk about us with your friends.
- **Give us feedback.** Tell us what we're doing well or where we can improve. Please upvote (👍) the issues that you are the most interested in seeing solved.
- **Help new users.** You can answer questions on StackOverflow or GitHub Discussions
- **Make changes happen.** Suggest changes to the documentation or code.
- **Write guides** If you come with a cool workflow, write about and we'll feature it in the blog or on the resources page
- **Report bugs** or missing features by creating an issue.
- **Review and comment** on existing pull requests and issues.

## Working on your first Pull Request?

You can learn how from this free video series:

[How to Contribute to a Project on GitHub](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github)

To help you get your feet wet and get you familiar with our contribution process, we have a list of [good first issues](https://github.com/formium/formik/issues?q=is:open+is:issue+label:"good+first+issue") that contain changes that have a relatively limited scope. This label means that there is already a working solution to the issue in the discussion section. Therefore, it is a great place to get started.

If you decide to fix an issue, please be sure to check the comment thread in case somebody is already working on a fix. If nobody is working on it at the moment, please leave a comment stating that you have started to work on it so other people don't accidentally duplicate your effort.

If somebody claims an issue but doesn't follow up for more than a week, it's fine to take it over but you should still leave a comment.
If there has been no activity on the issue for 7 to 14 days, it is safe to assume that nobody is working on it.

## Sending a Pull Request

Formik is a community project, so [Pull Requests](https://docs.github.com/en/free-pro-team@latest/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request) are always welcome, but, before working on a large change, it is best to open an issue first to discuss it with the maintainers.

When in doubt, keep your Pull Requests small. To give a Pull Request the best chance of getting accepted, don't bundle more than one feature or bug fix per Pull Request. It's often best to create two smaller Pull Requests than one big one.

1. [Fork the repository](https://docs.github.com/en/free-pro-team@latest/github/getting-started-with-github/fork-a-repo).

2. Clone the fork to your local machine and add upstream remote:

```sh
git clone https://github.com/<your username>/formik.git
cd formik
git remote add upstream https://github.com/formik/formik.git
```

3. Synchronize your local `next` branch with the upstream one:

```sh
git checkout main
git pull upstream main
```

4. Install the dependencies with [yarn](https://yarnpkg.com) (npm isn't supported):

```sh
yarn install
```

5. Create a new topic branch:

```sh
git checkout -b my-topic-branch
```

6. Make changes, commit and push to your fork:

```sh
git push -u origin HEAD
```

7. Go to [the repository](https://github.com/formium/formik) and [make a Pull Request](https://docs.github.com/en/free-pro-team@latest/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request).

The core team is monitoring for Pull Requests. We will review your Pull Request and either merge it, request changes to it, or close it with an explanation.

## Working locally

The repo is managed with Lerna, Yarn Workspaces, and TSDX.

### Develop

```shell
yarn install
yarn dev
```

### Test

Runs jest on all projects

```
yarn test
```

## How to increase the chance of a change being accepted?

The continuous integration service runs a series of checks automatically when a Pull Request is opened. If you're not
sure if your changes will pass, you can always open a Pull Request and the GitHub UI will display a summary of
the results. If any of them fail, refer to [Checks and how to fix them](#checks-and-how-to-fix-them).

Make sure the following is true:

- The branch is targeted at `main` for ongoing development. We do our best to keep `main` in good shape, with all tests passing. Code that lands in `main` must be compatible with the latest stable release. It may contain additional features, but no breaking changes. We should be able to release a new minor version from the tip of `main` at any time.
- If a feature is being added:
  - If the result was already achievable with the library, explain why this feature needs to be added.
  - If this is a common use case, consider adding an example to the documentation.
- When adding new features or modifying existing, please include tests to confirm the new behavior.
- The branch is not behind its target. (We use https://kodiakhq.com) to try to automate this process for you.

Because we will only merge a Pull Request for which all tests pass. The following items need to be correct. We will provide assistance if not:

- The code is formatted (run `yarn format`).
- The code is linted (run `yarn lint`).
- The Pull Request title is written imperatively. See [How to Write a Git Commit Message](https://chris.beams.io/posts/git-commit/#imperative) for a great explanation)
- If you have made a change that impacts semantic versioning, include a [changeset](../.changeset/README.md) by running `yarn changeset` and describing the change you've made. These get rolled together into release notes.

## Working locally

### Watching / Building packages

```
yarn dev
```

### Unit testing

This will run `Jest` unit tests

```
yarn test
```

### Playground / Integration testing

There is a Next.js playground that also serves as the app used for integration tests. What's cool is you can run Formik's build setup, next.js, and playwright all at the same time and everything will just magically "work" and live reload whenever you make a change.
This is the suggested development workflow going forward.

1. From the root, open a terminal and run `yarn dev` to start [TSDX](https://tsdx.io) watch on all packages
2. Then start the playground app with `yarn start:app` in another terminal window (it will boot to http://localhost:3000)
3. And finally, you can open a third tab to run playwright
   - You can use playwright UI using `yarn e2e:ui`
   - Or, if you'd rather not deal GUI, just run `yarn e2e`


================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms

github: [jaredpalmer] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: formik
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']


================================================
FILE: .github/ISSUE_TEMPLATE/1.Bug-report.md
================================================
---
name: Bug report
about: Create a bug report for Formik / examples
title: ''
labels: 'Type: Bug'
assignees: ''
---

## Bug report

### Current Behavior

<!-- If applicable, add screenshots to help explain your problem. -->

### Expected behavior

<!-- A clear and concise description of what you expected to happen. -->

### Reproducible example

<!-- Use one of the Codesandbox templates: -->

<!-- Formik template: https://codesandbox.io/s/91q6rxmmrp -->

<!-- withFormik template: https://codesandbox.io/s/437wy20rx4 -->

### Suggested solution(s)

<!-- How could we solve this bug? What changes would need to made to Formik? -->

### Additional context

<!-- Add any other context about the problem here.  -->

### Your environment

<!-- PLEASE FILL THIS OUT -->

| Software         | Version(s) |
| ---------------- | ---------- |
| Formik           |
| React            |
| TypeScript       |
| Browser          |
| npm/Yarn         |
| Operating System |


================================================
FILE: .github/ISSUE_TEMPLATE/2.Feature-request.md
================================================
---
name: Feature request
about: Request a new feature for Formik
title: ''
labels: 'Type: Feature Request'
assignees: ''
---

## Feature request

### Current Behavior

<!-- A clear and concise description of what is the current behavior / use.  -->

### Desired Behavior

<!-- A clear and concise description of what you want to happen.  -->

### Suggested Solution

<!-- Suggest a solution that the community/maintainers/you may take to enable the desired behavior  -->

<!-- NOTE: Feature Requests without suggested solutions may not be addressed or treated with the same level of urgency as those that have suggested solutions. -->

### Who does this impact? Who is this for?

<!-- Who is this for? All users? TypeScript users? Beginners? Advanced? Yourself? People using X, Y, X, etc.? -->

### Describe alternatives you've considered

<!-- A clear and concise description of any alternative solutions or features you've considered.  -->

### Additional context

<!-- Add any other context or links about the feature request here. -->


================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
contact_links:
  - name: Ask a question
    url: https://github.com/formium/formik/discussions
    about: Ask questions and discuss with other community members
  - name: Join the Discord server
    url: https://discord.gg/pJSg287
    about: Chat with other community members in real-time


================================================
FILE: .github/workflows/ci.yml
================================================
name: ci

on:
  pull_request:
  push:
    branches: [main]

jobs:
  detectChangedSourceFiles:
    name: 'determine changes'
    runs-on: ubuntu-latest
    outputs:
      changes: ${{ steps.changed-files-yaml.outputs.any_changed }}
    steps:
      - uses: actions/checkout@v4
      - name: Detect changed files
        id: changed-files-yaml
        uses: tj-actions/changed-files@v45
        with:
          files: |
            .github/workflows/ci.yml
            packages/formik/src/**
            packages/formik/package.json
            packages/formik-native/src/**
            packages/formik-native/package.json

  benchmark:
    if: always() && needs.detectChangedSourceFiles.outputs.changes == 'true'
    needs: detectChangedSourceFiles
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          cache: yarn
          node-version-file: .nvmrc

      - name: Install & build
        run: |
          node --version
          npm --version
          yarn --version
          yarn install --frozen-lockfile
          yarn build:benchmark

      - name: Download previous benchmark data
        uses: actions/cache@v4
        with:
          path: ./benchmark-cache
          key: ${{ runner.os }}-benchmark

      - name: Run benchmark
        run: yarn benchmark

      - name: Store benchmark result
        uses: benchmark-action/github-action-benchmark@v1
        with:
          tool: benchmarkjs
          external-data-json-path: ./benchmark-cache/benchmark-data.json
          output-file-path: output.txt
          # comment for PRs that's updated with current perf relative to baseline (main)
          summary-always: true
          # warn if slowness is detected; might be transient on rerun
          alert-threshold: 110%
          comment-on-alert: true
          fail-on-alert: true
          # if things get considerably slower, deny the PR
          fail-threshold: 120%
          # needed for commenting on PRs
          github-token: ${{ secrets.GITHUB_TOKEN }}

  interaction:
    needs: detectChangedSourceFiles
    if: always() && needs.detectChangedSourceFiles.outputs.changes == 'true'
    timeout-minutes: 10
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          cache: yarn
          node-version-file: .nvmrc

      - name: Install dependencies
        run: yarn install --frozen-lockfile

      - name: Get installed Playwright version
        id: playwright-version
        run: echo "PLAYWRIGHT_VERSION=$(node -e "console.log(require('./package-lock.json').dependencies['@playwright/test'].version)")" >> $GITHUB_ENV

      - name: Cache playwright binaries
        uses: actions/cache@v4
        id: playwright-cache
        with:
          path: |
            ~/.cache/ms-playwright
          key: ${{ runner.os }}-playwright-${{ env.PLAYWRIGHT_VERSION }}

      - name: Install Playwright Browsers
        run: yarn playwright install --with-deps
        if: steps.playwright-cache.outputs.cache-hit != 'true'
      - run: yarn playwright install-deps
        if: steps.playwright-cache.outputs.cache-hit != 'true'

      - name: Run Playwright tests
        run: yarn playwright test
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: playwright-report
          path: playwright-report/
          retention-days: 5

  size:
    needs: detectChangedSourceFiles
    if: always() && needs.detectChangedSourceFiles.outputs.changes == 'true'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 1
      - uses: preactjs/compressed-size-action@v2
        with:
          repo-token: '${{ secrets.GITHUB_TOKEN }}'
          build-script: 'turbo run build --filter {./packages/*}...'

  unit:
    needs: detectChangedSourceFiles
    if: always() && needs.detectChangedSourceFiles.outputs.changes == 'true'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          cache: yarn
          node-version-file: .nvmrc
      - name: Install deps, build, and test
        run: |
          node --version
          npm --version
          yarn --version
          yarn install --frozen-lockfile
          yarn test --coverage
        env:
          CI: true
          NODE_OPTIONS: --max-old-space-size=4096

================================================
FILE: .github/workflows/release.yml
================================================
name: Release
on:
  push:
    branches:
      - main
      - next
jobs:
  release:
    runs-on: ubuntu-latest
    if: github.repository == 'jaredpalmer/formik'
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - uses: actions/setup-node@v4
        with:
          cache: yarn
          node-version-file: .nvmrc

      - name: Install Dependencies
        run: yarn install

      - name: Create Release Pull Request or Publish to npm
        uses: changesets/action@v1.5.3
        with:
          publish: yarn release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}


================================================
FILE: .github/workflows/stale.yml
================================================
name: "Close stale issues/prs"
on:
  schedule:
    - cron: "1 0 * * *"

jobs:
  stale:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/stale@v9
        with:
          repo-token: ${{ secrets.GITHUB_TOKEN }}
          days-before-stale: 30
          days-before-close: 60
          stale-issue-label: "stale"
          stale-pr-label: "stale"
          stale-pr-message: "This pull request is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 60 days"
          stale-issue-message: "This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 60 days"
          any-of-labels: "Resolution: Duplicate,Resolution: Invalid,Resolution: Support Redirect,Resolution: Unsolved,Resolution: User Land,Resolution: Wontfix,Resolution: Workaround,Status: Author Feedback,Status: Needs More Information"


================================================
FILE: .gitignore
================================================
dist
compiled
*.log
coverage
.DS_Store
next.d.ts
legacy.d.ts
.idea
*.orig
output.txt

node_modules
package-lock.json
yarn.lock
!/docs/yarn.lock
!/yarn.lock

website/translated_docs
website/build
!website/yarn.lock
website/node_modules
website/i18n
!website2/yarn.lock
.env
.vercel
/test-results/
/playwright-report/
/playwright/.cache/
# Turborepo cache
.turbo


================================================
FILE: .kodiak.toml
================================================
# .kodiak.toml
version = 1

[merge]
automerge_label = "automerge"
require_automerge_label = false
method = "squash"
delete_branch_on_merge = true
optimistic_updates = true
prioritize_ready_to_merge = true
notify_on_conflict = false

[merge.message]
title = "pull_request_title"
body = "pull_request_body"
include_pr_number = true
body_type = "markdown"
strip_html_comments = true

================================================
FILE: .nvmrc
================================================
v18


================================================
FILE: .prettierrc
================================================
{
  "tabWidth": 2,
  "trailingComma": "es5",
  "semi": true,
  "singleQuote": true,
  "arrowParens": "avoid"
}


================================================
FILE: .vscode/settings.json
================================================
{
  "typescript.tsdk": "node_modules/typescript/lib",
  "editor.formatOnSave": false,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit"
  },
}


================================================
FILE: LICENSE
================================================
                             Apache License
                       Version 2.0, January 2004
                    https://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

  "License" shall mean the terms and conditions for use, reproduction,
  and distribution as defined by Sections 1 through 9 of this document.

  "Licensor" shall mean the copyright owner or entity authorized by
  the copyright owner that is granting the License.

  "Legal Entity" shall mean the union of the acting entity and all
  other entities that control, are controlled by, or are under common
  control with that entity. For the purposes of this definition,
  "control" means (i) the power, direct or indirect, to cause the
  direction or management of such entity, whether by contract or
  otherwise, or (ii) ownership of fifty percent (50%) or more of the
  outstanding shares, or (iii) beneficial ownership of such entity.

  "You" (or "Your") shall mean an individual or Legal Entity
  exercising permissions granted by this License.

  "Source" form shall mean the preferred form for making modifications,
  including but not limited to software source code, documentation
  source, and configuration files.

  "Object" form shall mean any form resulting from mechanical
  transformation or translation of a Source form, including but
  not limited to compiled object code, generated documentation,
  and conversions to other media types.

  "Work" shall mean the work of authorship, whether in Source or
  Object form, made available under the License, as indicated by a
  copyright notice that is included in or attached to the work
  (an example is provided in the Appendix below).

  "Derivative Works" shall mean any work, whether in Source or Object
  form, that is based on (or derived from) the Work and for which the
  editorial revisions, annotations, elaborations, or other modifications
  represent, as a whole, an original work of authorship. For the purposes
  of this License, Derivative Works shall not include works that remain
  separable from, or merely link (or bind by name) to the interfaces of,
  the Work and Derivative Works thereof.

  "Contribution" shall mean any work of authorship, including
  the original version of the Work and any modifications or additions
  to that Work or Derivative Works thereof, that is intentionally
  submitted to Licensor for inclusion in the Work by the copyright owner
  or by an individual or Legal Entity authorized to submit on behalf of
  the copyright owner. For the purposes of this definition, "submitted"
  means any form of electronic, verbal, or written communication sent
  to the Licensor or its representatives, including but not limited to
  communication on electronic mailing lists, source code control systems,
  and issue tracking systems that are managed by, or on behalf of, the
  Licensor for the purpose of discussing and improving the Work, but
  excluding communication that is conspicuously marked or otherwise
  designated in writing by the copyright owner as "Not a Contribution."

  "Contributor" shall mean Licensor and any individual or Legal Entity
  on behalf of whom a Contribution has been received by Licensor and
  subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of
  this License, each Contributor hereby grants to You a perpetual,
  worldwide, non-exclusive, no-charge, royalty-free, irrevocable
  copyright license to reproduce, prepare Derivative Works of,
  publicly display, publicly perform, sublicense, and distribute the
  Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of
  this License, each Contributor hereby grants to You a perpetual,
  worldwide, non-exclusive, no-charge, royalty-free, irrevocable
  (except as stated in this section) patent license to make, have made,
  use, offer to sell, sell, import, and otherwise transfer the Work,
  where such license applies only to those patent claims licensable
  by such Contributor that are necessarily infringed by their
  Contribution(s) alone or by combination of their Contribution(s)
  with the Work to which such Contribution(s) was submitted. If You
  institute patent litigation against any entity (including a
  cross-claim or counterclaim in a lawsuit) alleging that the Work
  or a Contribution incorporated within the Work constitutes direct
  or contributory patent infringement, then any patent licenses
  granted to You under this License for that Work shall terminate
  as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the
  Work or Derivative Works thereof in any medium, with or without
  modifications, and in Source or Object form, provided that You
  meet the following conditions:

  (a) You must give any other recipients of the Work or
      Derivative Works a copy of this License; and

  (b) You must cause any modified files to carry prominent notices
      stating that You changed the files; and

  (c) You must retain, in the Source form of any Derivative Works
      that You distribute, all copyright, patent, trademark, and
      attribution notices from the Source form of the Work,
      excluding those notices that do not pertain to any part of
      the Derivative Works; and

  (d) If the Work includes a "NOTICE" text file as part of its
      distribution, then any Derivative Works that You distribute must
      include a readable copy of the attribution notices contained
      within such NOTICE file, excluding those notices that do not
      pertain to any part of the Derivative Works, in at least one
      of the following places: within a NOTICE text file distributed
      as part of the Derivative Works; within the Source form or
      documentation, if provided along with the Derivative Works; or,
      within a display generated by the Derivative Works, if and
      wherever such third-party notices normally appear. The contents
      of the NOTICE file are for informational purposes only and
      do not modify the License. You may add Your own attribution
      notices within Derivative Works that You distribute, alongside
      or as an addendum to the NOTICE text from the Work, provided
      that such additional attribution notices cannot be construed
      as modifying the License.

  You may add Your own copyright statement to Your modifications and
  may provide additional or different license terms and conditions
  for use, reproduction, or distribution of Your modifications, or
  for any such Derivative Works as a whole, provided Your use,
  reproduction, and distribution of the Work otherwise complies with
  the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise,
  any Contribution intentionally submitted for inclusion in the Work
  by You to the Licensor shall be under the terms and conditions of
  this License, without any additional terms or conditions.
  Notwithstanding the above, nothing herein shall supersede or modify
  the terms of any separate license agreement you may have executed
  with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade
  names, trademarks, service marks, or product names of the Licensor,
  except as required for reasonable and customary use in describing the
  origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or
  agreed to in writing, Licensor provides the Work (and each
  Contributor provides its Contributions) on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  implied, including, without limitation, any warranties or conditions
  of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
  PARTICULAR PURPOSE. You are solely responsible for determining the
  appropriateness of using or redistributing the Work and assume any
  risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,
  whether in tort (including negligence), contract, or otherwise,
  unless required by applicable law (such as deliberate and grossly
  negligent acts) or agreed to in writing, shall any Contributor be
  liable to You for damages, including any direct, indirect, special,
  incidental, or consequential damages of any character arising as a
  result of this License or out of the use or inability to use the
  Work (including but not limited to damages for loss of goodwill,
  work stoppage, computer failure or malfunction, or any and all
  other commercial damages or losses), even if such Contributor
  has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing
  the Work or Derivative Works thereof, You may choose to offer,
  and charge a fee for, acceptance of support, warranty, indemnity,
  or other liability obligations and/or rights consistent with this
  License. However, in accepting such obligations, You may act only
  on Your own behalf and on Your sole responsibility, not on behalf
  of any other Contributor, and only if You agree to indemnify,
  defend, and hold each Contributor harmless for any liability
  incurred by, or claims asserted against, such Contributor by reason
  of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

Copyright 2020 Formik, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


================================================
FILE: SECURITY.md
================================================
# Security Policy

## Supported Versions

| Version | Supported          |
| ------- | ------------------ |
| 2.x.x     | :white_check_mark: |
| 1.5.x   | :white_check_mark:   |
| <= 1.4   | :x:               |

## Reporting a Vulnerability

Send a Twitter DM to [@jaredpalmer](http://twitter.com/@jaredpalmer) or an email to security@jaredpalmer.com



================================================
FILE: app/.gitignore
================================================
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local

# vercel
.vercel


================================================
FILE: app/README.md
================================================
# Formik Integration Test App

This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).


================================================
FILE: app/next-env.d.ts
================================================
/// <reference types="next" />
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.


================================================
FILE: app/package.json
================================================
{
  "name": "app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "formik": "latest",
    "next": "^12.0.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "yup": "^0.29.3"
  },
  "devDependencies": {
    "typescript": "^4.0.0"
  }
}


================================================
FILE: app/pages/_app.js
================================================
import React from 'react';
import '../styles/globals.css';

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

export default MyApp;


================================================
FILE: app/pages/basic.js
================================================
import React from 'react';
import { Formik, Field, Form, ErrorMessage } from 'formik';
import * as Yup from 'yup';

const Basic = () => {
  const renderCount = React.useRef(0);
  return (
    <div>
      <h1>Sign Up</h1>
      <Formik
        initialValues={{
          firstName: '',
          lastName: '',
          email: '',
          favorite: '',
          checked: [],
          picked: '',
        }}
        validationSchema={Yup.object().shape({
          email: Yup.string()
            .email('Invalid email address')
            .required('Required'),
          firstName: Yup.string().required('Required'),
          lastName: Yup.string()
            .min(2, 'Must be longer than 2 characters')
            .max(20, 'Nice try, nobody has a last name that long')
            .required('Required'),
        })}
        onSubmit={async values => {
          await new Promise(r => setTimeout(r, 500));
          alert(JSON.stringify(values, null, 2));
        }}
      >
        <Form>
          <Field name="firstName" placeholder="Jane" />
          <ErrorMessage name="firstName" component="p" />

          <Field name="lastName" placeholder="Doe" />
          <ErrorMessage name="lastName" component="p" />

          <Field
            id="email"
            name="email"
            placeholder="jane@acme.com"
            type="email"
          />
          <ErrorMessage name="email" component="p" />

          <label>
            <Field type="checkbox" name="toggle" />
            <span style={{ marginLeft: 3 }}>Toggle</span>
          </label>

          <div id="checkbox-group">Checkbox Group </div>
          <div role="group" aria-labelledby="checkbox-group">
            <label>
              <Field type="checkbox" name="checked" value="One" />
              One
            </label>
            <label>
              <Field type="checkbox" name="checked" value="Two" />
              Two
            </label>
            <label>
              <Field type="checkbox" name="checked" value="Three" />
              Three
            </label>
          </div>
          <div id="my-radio-group">Picked</div>
          <div role="group" aria-labelledby="my-radio-group">
            <label>
              <Field type="radio" name="picked" value="One" />
              One
            </label>
            <label>
              <Field type="radio" name="picked" value="Two" />
              Two
            </label>
          </div>
          <button type="submit">Submit</button>
          <div id="renderCounter">{renderCount.current++}</div>
        </Form>
      </Formik>
    </div>
  );
};

export default Basic;


================================================
FILE: app/pages/index.tsx
================================================
import React from 'react';
import Link from 'next/link';

function Home() {
  return (
    <main>
      <h1>Formik Examples and Fixtures</h1>
      <ul>
        <li>
          <Link href="/basic">Basic</Link>
        </li>
        <li>
          <Link href="/async-submission">Async Submission</Link>
        </li>
      </ul>
      <style jsx>{`
        main {
          max-width: 500px;
          margin: 2rem auto;
          padding-bottom: 20rem;
        }
        a {
          display: block;
          margin-top: 0.5rem;
          margin-bottom: 0.5rem;
          color: rgb(68, 122, 221);
          text-decoration: underline;
          font-size: 20px;
        }
        ul {
          margin: 0;
          padding: 0;
        }
        li {
          margin-left: 1rem;
        }
      `}</style>
    </main>
  );
}

export default Home;


================================================
FILE: app/pages/sign-in.js
================================================
import React, { useEffect, useState } from 'react';
import { ErrorMessage, Field, Form, FormikProvider, useFormik } from 'formik';
import * as Yup from 'yup';
import { useRouter } from 'next/router';

const SignIn = () => {
  const router = useRouter();
  const [errorLog, setErrorLog] = useState([]);

  const formik = useFormik({
    validateOnMount: router.query.validateOnMount === 'true',
    validateOnBlur: router.query.validateOnBlur !== 'false',
    validateOnChange: router.query.validateOnChange !== 'false',
    initialValues: { username: '', password: '' },
    validationSchema: Yup.object().shape({
      username: Yup.string().required('Required'),
      password: Yup.string().required('Required'),
    }),
    onSubmit: async values => {
      await new Promise(r => setTimeout(r, 500));
      alert(JSON.stringify(values, null, 2));
    },
  });

  useEffect(() => {
    if (formik.errors.username && formik.touched.username) {
      setErrorLog(logs => [
        ...logs,
        {
          name: 'username',
          value: formik.values.username,
          error: formik.errors.username,
        },
      ]);
    }

    if (formik.errors.password && formik.touched.password) {
      setErrorLog(logs => [
        ...logs,
        {
          name: 'password',
          value: formik.values.password,
          error: formik.errors.password,
        },
      ]);
    }
  }, [
    formik.values.username,
    formik.errors.username,
    formik.touched.username,
    formik.values.password,
    formik.errors.password,
    formik.touched.password,
  ]);

  return (
    <div>
      <h1>Sign In</h1>

      <FormikProvider value={formik}>
        <Form>
          <div>
            <Field name="username" placeholder="Username" />
            <ErrorMessage name="username" component="p" />
          </div>

          <div>
            <Field name="password" placeholder="Password" type="password" />
            <ErrorMessage name="password" component="p" />
          </div>

          <button type="submit" disabled={!formik.isValid}>
            Submit
          </button>

          <button
            type="reset"
            onClick={() => {
              setErrorLog([]);
            }}
          >
            Reset
          </button>

          <pre id="error-log">{JSON.stringify(errorLog, null, 2)}</pre>
        </Form>
      </FormikProvider>
    </div>
  );
};

export default SignIn;


================================================
FILE: app/styles/globals.css
================================================
html,
body {
  padding: 0;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
    Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}

a {
  color: inherit;
  text-decoration: none;
}

* {
  box-sizing: border-box;
}


================================================
FILE: app/tsconfig.json
================================================
{
  "extends": "../tsconfig.base.json",
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "jsx": "preserve",
    "allowJs": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "incremental": true
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}


================================================
FILE: docs/3rd-party-bindings.md
================================================
---
title: 3rd Party Bindings
original_id: 3rd-party-bindings
description: Use Formik with popular React component libraries like Material UI, Bootstrap, AntD, Semantic UI, and more.
---

If you would like to use Formik with a UI framework, you'll probably want to create a wrapper component that binds Formik's props and callbacks.

A few popular frameworks have open source wrappers readily available:

- [Ant Design](https://github.com/jannikbuschke/formik-antd)
- [Fabric](https://github.com/kmees/formik-office-ui-fabric-react)
- [Material UI](https://github.com/stackworx/formik-material-ui)
- [Reactstrap](https://github.com/shoaibkhan94/reactstrap-formik)
- [Semantic UI 2.0](https://github.com/JT501/formik-semantic-ui-react)
- [Semantic UI](https://github.com/turner-industries/formik-semantic-ui)


================================================
FILE: docs/api/connect.md
================================================
---
id: connect
title: connect()
---

`connect()` is a higher-order component (HoC) that allows you to hook anything into Formik's context. It is used internally to construct `<Field>` and `<Form>`, but you can use it to build out new components as your needs change.

## Type signature

```tsx
connect<OuterProps, Values = any>(Comp: React.ComponentType<OuterProps & { formik: FormikContext<Values> }>) => React.ComponentType<OuterProps>
```

## Example

```jsx
import React from 'react';
import { connect, getIn } from 'formik';

// This component renders an error message if a field has
// an error and it's already been touched.
const ErrorMessage = props => {
  // All FormikProps available on props.formik!
  const error = getIn(props.formik.errors, props.name);
  const touch = getIn(props.formik.touched, props.name);
  return touch && error ? error : null;
};

export default connect(ErrorMessage);
```


================================================
FILE: docs/api/errormessage.md
================================================
---
id: errormessage
title: <ErrorMessage />
---

`<ErrorMessage />` is a component that renders the error message of a given field if that field has been visited (i.e.`touched[name] === true`) (and there is an `error` message present). It expects that all error messages are stored for a given field as a string. Like `<Field />`, `<FastField />`, and `<FieldArray />`, lodash-like dot path and bracket syntax is supported.

## Example

```diff
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from "yup";

const SignupSchema = Yup.object().shape({
  name: Yup.string()
    .min(2, 'Too Short!')
    .max(70, 'Too Long!')
    .required('Required'),
  email: Yup.string()
    .email('Invalid email')
    .required('Required'),
});

export const ValidationSchemaExample = () => (
  <div>
    <h1>Signup</h1>
    <Formik
      initialValues={{
        name: '',
        email: '',
      }}
      validationSchema={SignupSchema}
      onSubmit={values => {
        // same shape as initial values
        console.log(values);
      }}
    >
      {({ errors, touched }) => (
        <Form>
          <Field name="name"  />
-           {errors.name && touched.name ? (
-            <div>{errors.name}</div>
-          ) : null}
+         <ErrorMessage name="name" />
          <Field name="email" type="email" />
-           {errors.email && touched.email ? (
-            <div>{errors.email}</div>
-          ) : null}
+         <ErrorMessage name="email" />
          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  </div>
);
```

#### Props

---

# Reference

## Props

### `children`

`children?: ((message: string) => React.ReactNode)`

A function that returns a valid React element. Will only be called when the field has been touched and an error exists.

```jsx
// the render callback will only be called when the
// field has been touched and an error exists and subsequent updates.
<ErrorMessage name="email">{msg => <div>{msg}</div>}</ErrorMessage>
```

### `component`

`component?: string | React.ComponentType<FieldProps>`

Either a React component or the name of an HTML element to render. If not specified, `<ErrorMessage>` will just return a string.

```jsx
<ErrorMessage component="div" name="email" />
// --> {touched.email && error.email ? <div>{error.email}</div> : null}

<ErrorMessage component="span" name="email" />
// --> {touched.email && error.email ? <span>{error.email}</span> : null}

<ErrorMessage component={Custom} name="email" />
// --> {touched.email && error.email ? <Custom>{error.email}</Custom> : null}

<ErrorMessage name="email" />
// This will return a string. React 16+.
// --> {touched.email && error.email ? error.email : null}
```

### `id`

`id?: string`

A field's id in Formik state. To get access to DOM elements for e2e testing purposes, it doesn't impact the implementation in any way as the prop can still be omitted. 
```jsx
// id will be used only for testing purposes
// not contributing anything to the core implementation.
<ErrorMessage name="email" id="form_email_id" />
```

### `name`

`name: string`
**Required**

A field's name in Formik state. To access nested objects or arrays, name can also accept lodash-like dot path like `social.facebook` or `friends[0].firstName`

### `render`

`render?: (error: string) => React.ReactNode`

A function that returns a valid React element. Will only be called when the field has been touched and an error exists.

```jsx
// the render callback will only be called when the
// field has been touched and an error exists and subsequent updates.
<ErrorMessage name="email" render={msg => <div>{msg}</div>} />
```


================================================
FILE: docs/api/fastfield.md
================================================
---
id: fastfield
title: <FastField />
---

## Before we start

`<FastField />` is meant for performance _optimization_. However, you really do not need to use it until you do. Only proceed if you are familiar with how React's [`shouldComponentUpdate()`](https://reactjs.org/docs/react-component.html#shouldcomponentupdate) works. You have been warned.

**No. Seriously. Please review the following parts of the official React documentation before continuing**

- [React `shouldComponentUpdate()` Reference](https://reactjs.org/docs/react-component.html#shouldcomponentupdate)
- [`shouldComponentUpdate` in Action](https://reactjs.org/docs/optimizing-performance.html#shouldcomponentupdate-in-action)

## Overview

`<FastField />` is an optimized version of `<Field />` meant to be used on large forms (~30+ fields) or when a field has very expensive validation requirements. `<FastField />` has the same exact API as `<Field>`, but implements `shouldComponentUpdate()` internally to block all additional re-renders unless there are direct updates to the `<FastField />`'s relevant parts/slice of Formik state.

For example, `<FastField name="firstName" />` will only re-render when there are:

- Changes to `values.firstName`, `errors.firstName`, `touched.firstName`, or `isSubmitting`. This is determined by shallow comparison. Note: dotpaths are supported.
- A prop is added/removed to the `<FastField name="firstName" />`
- The `name` prop changes

Other than for these aforementioned situations, `<FastField />` will not re-render when other parts of Formik state change. However, all updates triggered by a `<FastField />` will trigger re-renders to other "vanilla" `<Field />` components.

## When to use `<FastField />`

**If a `<Field />` is "independent" of all other `<Field />`'s in your form, then you can use `<FastField />`**.

More specifically, if the `<Field />` does not change behavior or render anything that is based on updates to another `<Field />` or `<FastField />`'s slice of Formik state AND it does not rely on other parts of top-level `<Formik />` state (e.g. `isValidating`, `submitCount`), then you can use `<FastField />` as a drop-in replacement to `<Field />`.

## Example

```jsx
import React from 'react';
import { Formik, Field, FastField, Form } from 'formik';
import * as Yup from 'yup';

const Basic = () => (
  <div>
    <h1>Sign Up</h1>
    <Formik
      initialValues={{
        firstName: '',
        lastName: '',
        email: '',
      }}
      validationSchema={Yup.object().shape({
        firstName: Yup.string().required(),
        middleInitial: Yup.string(),
        lastName: Yup.string().required(),
        email: Yup.string().email().required(),
      })}
      onSubmit={values => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
        }, 500);
      }}
    >
      {formikProps => (
        <Form>
          {/** This <FastField> only updates for changes made to
           values.firstName, touched.firstName, errors.firstName */}
          <label htmlFor="firstName">First Name</label>
          <FastField name="firstName" placeholder="Weezy" />

          {/** Updates for all changes because it's from the
           top-level formikProps which get all updates */}
          {formikProps.touched.firstName && formikProps.errors.firstName && (
            <div>{formikProps.errors.firstName}</div>
          )}

          <label htmlFor="middleInitial">Middle Initial</label>
          <FastField name="middleInitial" placeholder="F">
            {({ field, form, meta }) => (
              <div>
                <input {...field} />
                {/**
                 * This updates normally because it's from the same slice of Formik state,
                 * i.e. path to the object matches the name of this <FastField />
                 */}
                {meta.touched ? meta.error : null}

                {/** This won't ever update since it's coming from
                 from another <Field>/<FastField>'s (i.e. firstName's) slice   */}
                {form.touched.firstName && form.errors.firstName
                  ? form.errors.firstName
                  : null}

                {/* This doesn't update either */}
                {form.submitCount}

                {/* Imperative methods still work as expected */}
                <button
                  type="button"
                  onClick={form.setFieldValue('middleInitial', 'J')}
                >
                  J
                </button>
              </div>
            )}
          </FastField>

          {/** Updates for all changes to Formik state
           and all changes by all <Field>s and <FastField>s */}
          <label htmlFor="lastName">LastName</label>
          <Field name="lastName" placeholder="Baby">
            {({ field, form, meta }) => (
              <div>
                <input {...field} />
                {/**  Works because this is inside
                 of a <Field/>, which gets all updates */}
                {form.touched.firstName && form.errors.firstName
                  ? form.errors.firstName
                  : null}
              </div>
            )}
          </Field>

          {/** Updates for all changes to Formik state and
           all changes by all <Field>s and <FastField>s */}
          <label htmlFor="email">Email</label>
          <Field name="email" placeholder="jane@acme.com" type="email" />

          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  </div>
);
```


================================================
FILE: docs/api/field.md
================================================
---
id: field
title: <Field />
---

`<Field />` will automagically hook up inputs to Formik. It uses the `name`
attribute to match up with Formik state. `<Field />` will default to an HTML
`<input />` element.

## Rendering

There are a few different ways to render things with `<Field>`.

- `<Field as>`
- `<Field children>`
- `<Field component>`
- ~~`<Field render>`~~ _deprecated in 2.x. Using these will log warning_

`as` can either be a React component or the name of an HTML element to render. Formik will automagically inject `onChange`, `onBlur`, `name`, and `value` props of the field designated by the `name` prop to the (custom) component.

`children` can either be an array of elements (e.g. `<option>` in the case of `<Field as="select">`) or a callback function (a.k.a render prop). The render props are an object containing:

- `field`: An object containing `onChange`, `onBlur`, `name`, and `value` of the field (see [`FieldInputProps`](./useField#fieldinputpropsvalue))
- `form`: The Formik bag
- `meta`: An object containing metadata (i.e. `value`, `touched`, `error`, and `initialValue`) about the field (see [`FieldMetaProps`](./useField#fieldmetapropsvalue))

`component` can either be a React component or the name of an HTML element to render. All additional props will be passed through.

> In Formik 0.9 to 1.x, the `render` prop could also be used for rendering. It has been deprecated since 2.x. While the code still lives within `<Field>`, using `render` will show a warning in the console.

## Example

```jsx
import React from 'react';
import { Field, Form, Formik, FormikProps } from 'formik';

const MyInput = ({ field, form, ...props }) => {
  return <input {...field} {...props} />;
};

const Example = () => (
  <div>
    <h1>My Form</h1>
    <Formik
      initialValues={{ email: '', color: 'red', firstName: '', lastName: '' }}
      onSubmit={(values, actions) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          actions.setSubmitting(false);
        }, 1000);
      }}
    >
      {(props: FormikProps<any>) => (
        <Form>
          <Field type="email" name="email" placeholder="Email" />
          <Field as="select" name="color">
            <option value="red">Red</option>
            <option value="green">Green</option>
            <option value="blue">Blue</option>
          </Field>

          <Field name="lastName">
            {({
              field, // { name, value, onChange, onBlur }
              form: { touched, errors }, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc.
              meta,
            }) => (
              <div>
                <input type="text" placeholder="Email" {...field} />
                {meta.touched && meta.error && (
                  <div className="error">{meta.error}</div>
                )}
              </div>
            )}
          </Field>
          <Field name="lastName" placeholder="Doe" component={MyInput} />
          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  </div>
);
```

#### Props

---

# Reference

## Props

### `as`

`as?: string | React.ComponentType<FieldProps['field']>`

Either a React component or the name of an HTML element to render. That is, one of the following:

- `input`
- `select`
- `textarea`
- A valid HTML element name
- A custom React component

Custom React components will be passed `onChange`, `onBlur`, `name`, and `value` plus any other props passed directly to `<Field>`.

Default is `'input'` (so an `<input>` is rendered by default)

```jsx
// Renders an HTML <input> by default
<Field name="lastName" placeholder="Last Name"/>

// Renders an HTML <select>
<Field name="color" as="select">
  <option value="red">Red</option>
  <option value="green">Green</option>
  <option value="blue">Blue</option>
</Field>

// Renders a CustomInputComponent
<Field name="firstName" as={CustomInputComponent} placeholder="First Name"/>

const CustomInputComponent = (props) => (
  <input className="my-custom-input" type="text" {...props} />
);
```

### `children`

`children?: React.ReactNode | ((props: FieldProps) => React.ReactNode)`

Either JSX elements or callback function. Same as `render`.

```jsx
// Children can be JSX elements
<Field name="color" as="select">
  <option value="red">Red</option>
  <option value="green">Green</option>
  <option value="blue">Blue</option>
</Field>

// Or a callback function
<Field name="firstName">
{({ field, form, meta }) => (
  <div>
    <input type="text" {...field} placeholder="First Name"/>
    {meta.touched &&
      meta.error && <div className="error">{meta.error}</div>}
  </div>
)}
</Field>
```

### `component`

`component?: string | React.ComponentType<FieldProps>`

Either a React component or the name of an HTML element to render. That is, one of the following:

- `input`
- `select`
- `textarea`
- A custom React component

Custom React components will be passed `FieldProps` which is same `render` prop parameters of `<Field render>` plus any other props passed to directly to `<Field>`.

Default is `'input'` (so an `<input>` is rendered by default)

```jsx
// Renders an HTML <input> by default
<Field name="lastName" placeholder="Last Name"/>

// Renders an HTML <select>
<Field name="color" component="select">
  <option value="red">Red</option>
  <option value="green">Green</option>
  <option value="blue">Blue</option>
</Field>

// Renders a CustomInputComponent
<Field name="firstName" component={CustomInputComponent} placeholder="First Name"/>

const CustomInputComponent = ({
  field, // { name, value, onChange, onBlur }
  form: { touched, errors }, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc.
  ...props
}) => (
  <div>
    <input type="text" {...field} {...props} />
    {touched[field.name] &&
      errors[field.name] && <div className="error">{errors[field.name]}</div>}
  </div>
);
```

### `innerRef`

`innerRef?: (el: React.HTMLElement<any> => void)`

When you are **not** using a custom component and you need to access the underlying DOM node created by `Field` (e.g. to call `focus`), pass the callback to the `innerRef` prop instead.

### `name`

`name: string`

**Required**

A field's name in Formik state. To access nested objects or arrays, name can also accept lodash-like dot path like `social.facebook` or `friends[0].firstName`

### `render`

`render?: (props: FieldProps) => React.ReactNode`

**Deprecated in 2.x. Use `children` instead.**

A function that returns one or more JSX elements.

```jsx
// Renders an HTML <input> and passes FieldProps field property
<Field
  name="firstName"
  render={({ field /* { name, value, onChange, onBlur } */ }) => (
    <input {...field} type="text" placeholder="firstName" />
  )}
/>

// Renders an HTML <input> and disables it while form is submitting
<Field
  name="lastName"
  render={({ field, form: { isSubmitting } }) => (
    <input {...field} disabled={isSubmitting} type="text" placeholder="lastName" />
  )}
/>

// Renders an HTML <input> with custom error <div> element
<Field
  name="lastName"
  render={({ field, form: { touched, errors } }) => (
    <div>
      <input {...field} type="text" placeholder="lastName" />
      {touched[field.name] &&
        errors[field.name] && <div className="error">{errors[field.name]}</div>}
    </div>
  )}
/>
```

### `validate`

`validate?: (value: any) => undefined | string | Promise<any>`

You can run independent field-level validations by passing a function to the
`validate` prop. The function will respect the `validateOnBlur` and
`validateOnChange` config/props specified in the `<Field>'s` parent `<Formik>`
/ `withFormik`. This function can either be synchronous or asynchronous:

- Sync: if invalid, return a `string` containing the error message or
  return `undefined`.

- Async: return a Promise that resolves a `string` containing the error message.
  This works like Formik's `validate`, but instead of returning an `errors`
  object, it's just a `string`.

```jsx
import React from 'react';
import { Formik, Form, Field } from 'formik';

// Synchronous validation function
const validate = value => {
  let errorMessage;
  if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)) {
    errorMessage = 'Invalid email address';
  }
  return errorMessage;
};

// Async validation function
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

const validateAsync = value => {
  return sleep(2000).then(() => {
    if (['admin', 'null', 'god'].includes(value)) {
      return 'Nice try';
    }
  });
};

// example usage
const MyForm = () => (
  <Formik
    initialValues={{ email: '', username: '' }}
    onSubmit={values => alert(JSON.stringify(values, null, 2))}
  >
    {({ errors, touched }) => (
      <Form>
        <Field validate={validate} name="email" type="email" />
        {errors.email && touched.email ? <div>{errors.email}</div> : null}
        <Field validate={validateAsync} name="username" />
        {errors.username && touched.username ? (
          <div>{errors.username}</div>
        ) : null}
        <button type="submit">Submit</button>
      </Form>
    )}
  </Formik>
);
```

Note: To allow for i18n libraries, the TypeScript typings for `validate` are
slightly relaxed and allow you to return a `Function` (e.g. `i18n('invalid')`).


================================================
FILE: docs/api/fieldarray.md
================================================
---
id: fieldarray
title: <FieldArray />
---

`<FieldArray />` is a component that helps with common array/list manipulations. You pass it a `name` property with the path to the key within `values` that holds the relevant array. `<FieldArray />` will then give you access to array helper methods via render props. For convenience, calling these methods will trigger validation and also manage `touched` for you.

```jsx
import React from 'react';
import { Formik, Form, Field, FieldArray } from 'formik';

// Here is an example of a form with an editable list.
// Next to each input are buttons for insert and remove.
// If the list is empty, there is a button to add an item.
export const FriendList = () => (
  <div>
    <h1>Friend List</h1>
    <Formik
      initialValues={{ friends: ['jared', 'ian', 'brent'] }}
      onSubmit={values =>
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
        }, 500)
      }
      render={({ values }) => (
        <Form>
          <FieldArray
            name="friends"
            render={arrayHelpers => (
              <div>
                {values.friends && values.friends.length > 0 ? (
                  values.friends.map((friend, index) => (
                    <div key={index}>
                      <Field name={`friends.${index}`} />
                      <button
                        type="button"
                        onClick={() => arrayHelpers.remove(index)} // remove a friend from the list
                      >
                        -
                      </button>
                      <button
                        type="button"
                        onClick={() => arrayHelpers.insert(index, '')} // insert an empty string at a position
                      >
                        +
                      </button>
                    </div>
                  ))
                ) : (
                  <button type="button" onClick={() => arrayHelpers.push('')}>
                    {/* show this when user has removed all friends from the list */}
                    Add a friend
                  </button>
                )}
                <div>
                  <button type="submit">Submit</button>
                </div>
              </div>
            )}
          />
        </Form>
      )}
    />
  </div>
);
```

### `name: string`

The name or path to the relevant key in [`values`](./formik#values--field-string-any-).

### `validateOnChange?: boolean`

Default is `true`. Determines if form validation should or should not be run _after_ any array manipulations.

## FieldArray Array of Objects

You can also iterate through an array of objects, by following a convention of `object[index].property` or `object.index.property` for the name attributes of `<Field />` or `<input />` elements in `<FieldArray />`.

```jsx
<Form>
  <FieldArray
    name="friends"
    render={arrayHelpers => (
      <div>
        {values.friends.map((friend, index) => (
          <div key={index}>
            {/** both these conventions do the same */}
            <Field name={`friends[${index}].name`} />
            <Field name={`friends.${index}.age`} />

            <button type="button" onClick={() => arrayHelpers.remove(index)}>
              -
            </button>
          </div>
        ))}
        <button
          type="button"
          onClick={() => arrayHelpers.push({ name: '', age: '' })}
        >
          +
        </button>
      </div>
    )}
  />
</Form>
```

## FieldArray Validation Gotchas

Validation can be tricky with `<FieldArray>`.

If you use [`validationSchema`](./guides/validation.md#validationschema) and your form has array validation requirements (like a min length) as well as nested array field requirements, displaying errors can be tricky. Formik/Yup will show validation errors inside out. For example,

```js
const schema = Yup.object().shape({
  friends: Yup.array()
    .of(
      Yup.object().shape({
        name: Yup.string().min(4, 'too short').required('Required'), // these constraints take precedence
        salary: Yup.string().min(3, 'cmon').required('Required'), // these constraints take precedence
      })
    )
    .required('Must have friends') // these constraints are shown if and only if inner constraints are satisfied
    .min(3, 'Minimum of 3 friends'),
});
```

Since Yup and your custom validation function should always output error messages as strings, you'll need to sniff whether your nested error is an array or a string when you go to display it.

So...to display `'Must have friends'` and `'Minimum of 3 friends'` (our example's array validation constraints)...

**_Bad_**

```jsx
// within a `FieldArray`'s render
const FriendArrayErrors = errors =>
  errors.friends ? <div>{errors.friends}</div> : null; // app will crash
```

**_Good_**

```jsx
// within a `FieldArray`'s render
const FriendArrayErrors = errors =>
  typeof errors.friends === 'string' ? <div>{errors.friends}</div> : null;
```

For the nested field errors, you should assume that no part of the object is defined unless you've checked for it. Thus, you may want to do yourself a favor and make a custom `<ErrorMessage />` component that looks like this:

```jsx
import { Field, getIn } from 'formik';

const ErrorMessage = ({ name }) => (
  <Field
    name={name}
    render={({ form }) => {
      const error = getIn(form.errors, name);
      const touch = getIn(form.touched, name);
      return touch && error ? error : null;
    }}
  />
);

// Usage
<ErrorMessage name="friends[0].name" />; // => null, 'too short', or 'required'
```

_NOTE_: In Formik v0.12 / 1.0, a new `meta` prop may be added to `Field` and `FieldArray` that will give you relevant metadata such as `error` & `touch`, which will save you from having to use Formik or lodash's getIn or checking if the path is defined on your own.

## FieldArray Helpers

The following methods are made available via render props.

- `push: (obj: any) => void`: Add a value to the end of an array
- `swap: (indexA: number, indexB: number) => void`: Swap two values in an array
- `move: (from: number, to: number) => void`: Move an element in an array to another index
- `insert: (index: number, value: any) => void`: Insert an element at a given index into the array
- `unshift: (value: any) => number`: Add an element to the beginning of an array and return its length
- `remove<T>(index: number): T | undefined`: Remove an element at an index of an array and return it
- `pop<T>(): T | undefined`: Remove and return value from the end of the array
- `replace: (index: number, value: any) => void`: Replace a value at the given index into the array

## FieldArray render methods

There are three ways to render things with `<FieldArray />`

- `<FieldArray name="..." component>`
- `<FieldArray name="..." render>`
- `<FieldArray name="..." children>`

### `render: (arrayHelpers: ArrayHelpers) => React.ReactNode`

```jsx
import React from 'react';
import { Formik, Form, Field, FieldArray } from 'formik'

export const FriendList = () => (
  <div>
    <h1>Friend List</h1>
    <Formik
      initialValues={{ friends: ['jared', 'ian', 'brent'] }}
      onSubmit={...}
      render={formikProps => (
        <FieldArray
          name="friends"
          render={({ move, swap, push, insert, unshift, pop }) => (
            <Form>
              {/*... use these however you want */}
            </Form>
          )}
        />
    />
  </div>
);
```

### `component: React.ReactNode`

```jsx
import React from 'react';
import { Formik, Form, Field, FieldArray } from 'formik'


export const FriendList = () => (
  <div>
    <h1>Friend List</h1>
    <Formik
      initialValues={{ friends: ['jared', 'ian', 'brent'] }}
      onSubmit={...}
      render={formikProps => (
        <FieldArray
          name="friends"
          component={MyDynamicForm}
        />
      )}
    />
  </div>
);


// In addition to the array helpers, Formik state and helpers
// (values, touched, setXXX, etc) are provided through a `form`
// prop
export const MyDynamicForm = ({
  move, swap, push, insert, unshift, pop, form
}) => (
 <Form>
  {/**  whatever you need to do */}
 </Form>
);
```

### `children: func`

```jsx
import React from 'react';
import { Formik, Form, Field, FieldArray } from 'formik'


export const FriendList = () => (
  <div>
    <h1>Friend List</h1>
    <Formik
      initialValues={{ friends: ['jared', 'ian', 'brent'] }}
      onSubmit={...}
      render={formikProps => (
        <FieldArray name="friends">
          {({ move, swap, push, insert, unshift, pop, form }) => {
            return (
              <Form>
                {/*... use these however you want */}
              </Form>
            );
          }}
        </FieldArray>
      )}
    />
  </div>
);
```


================================================
FILE: docs/api/form.md
================================================
---
id: form
title: <Form />
---

Form is a small wrapper around an HTML `<form>` element that automatically hooks into Formik's `handleSubmit` and `handleReset`. All other props are passed directly through to the DOM node.

```jsx
// so...
<Form />

// is identical to this...
<form onReset={formikProps.handleReset} onSubmit={formikProps.handleSubmit} {...props} />
```


================================================
FILE: docs/api/formik.md
================================================
---
id: formik
title: <Formik />
---

`<Formik>` is a component that helps you with building forms. It uses a render
props pattern made popular by libraries like React Motion and React Router.

## Example

```jsx
import React from 'react';
import { Formik } from 'formik';

const BasicExample = () => (
  <div>
    <h1>My Form</h1>
    <Formik
      initialValues={{ name: 'jared' }}
      onSubmit={(values, actions) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          actions.setSubmitting(false);
        }, 1000);
      }}
    >
      {props => (
        <form onSubmit={props.handleSubmit}>
          <input
            type="text"
            onChange={props.handleChange}
            onBlur={props.handleBlur}
            value={props.values.name}
            name="name"
          />
          {props.errors.name && <div id="feedback">{props.errors.name}</div>}
          <button type="submit">Submit</button>
        </form>
      )}
    </Formik>
  </div>
);
```

#### Props

---

# Reference

## Props

### Formik render methods and props

There are 2 ways to render things with `<Formik />`

- `<Formik component>`
- `<Formik children>`
- ~~`<Formik render>`~~ Deprecated in 2.x

Each render methods will be passed the same props:

#### `dirty: boolean`

Returns `true` if values are not deeply equal from initial values, `false` otherwise.
`dirty` is a readonly computed property and should not be mutated directly.

#### `errors: { [field: string]: string }`

Form validation errors. Should match the shape of your form's `values` defined
in `initialValues`. If you are using `validationSchema` (which you should be),
keys and shape will match your schema exactly. Internally, Formik transforms raw
[Yup validation errors](https://github.com/jquense/yup#validationerrorerrors-string--arraystring-value-any-path-string)
on your behalf. If you are using `validate`, then that function will determine
the `errors` objects shape.

#### `handleBlur: (e: any) => void`

`onBlur` event handler. Useful for when you need to track whether an input has
been `touched` or not. This should be passed to `<input onBlur={handleBlur} ... />`

#### `handleChange: (e: React.ChangeEvent<any>) => void`

General input change event handler. This will update the `values[key]` where
`key` is the event-emitting input's `name` attribute. If the `name` attribute is
not present, `handleChange` will look for an input's `id` attribute. Note:
"input" here means all HTML inputs.

#### `handleReset: () => void`

Reset handler. Will reset the form to its initial state. This should be passed
to `<button onClick={handleReset}>...</button>`

#### `handleSubmit: (e: React.FormEvent<HTMLFormElement>) => void`

Submit handler. This should be passed to `<form onSubmit={props.handleSubmit}>...</form>`. To learn more about the submission process, see [Form Submission](../guides/form-submission.md).

#### `isSubmitting: boolean`

Submitting state of the form. Returns `true` if submission is in progress and `false` otherwise. IMPORTANT: Formik will set this to `true` as soon as submission is _attempted_. To learn more about the submission process, see [Form Submission](../guides/form-submission.md).

#### `isValid: boolean`

Returns `true` if there are no `errors` (i.e. the `errors` object is empty) and `false` otherwise.

> Note: `isInitialValid` was deprecated in 2.x. However, for backwards compatibility, if the `isInitialValid` prop is specified, `isValid` will return `true` if the there are no `errors`, or the result of `isInitialValid` of the form if it is in "pristine" condition (i.e. not `dirty`).

#### `isValidating: boolean`

Returns `true` if Formik is running validation during submission, or by calling [`validateForm`] directly `false` otherwise. To learn more about what happens with `isValidating` during the submission process, see [Form Submission](../guides/form-submission.md).

#### `resetForm: (nextState?: Partial<FormikState<Values>>) => void`

Imperatively reset the form. The only (optional) argument, `nextState`, is an object on which any of these `FormikState` fields are optional:

```ts
interface FormikState<Values> {
  /** Form values */
  values: Values;
  /** map of field names to specific error for that field */
  errors: FormikErrors<Values>;
  /** map of field names to **whether** the field has been touched */
  touched: FormikTouched<Values>;
  /** whether the form is currently submitting */
  isSubmitting: boolean;
  /** whether the form is currently validating (prior to submission) */
  isValidating: boolean;
  /** Top level status state, in case you need it */
  status?: any;
  /** Number of times user tried to submit the form */
  submitCount: number;
}
```

If `nextState` is specified, Formik will set `nextState.values` as the new "initial state" and use the related values of `nextState` to update the form's `initialValues` as well as `initialTouched`, `initialStatus`, `initialErrors`. This is useful for altering the initial state (i.e. "base") of the form after changes have been made.

```tsx
// typescript usage
function MyForm(props: MyFormProps) {
  // using TSX Generics here to set <Values> to <Blog>
  return (
    <Formik<Blog>
      initialValues={props.initVals}
      onSubmit={(values, actions) => {
        props.onSubmit(values).then(() => {
          actions.setSubmitting(false);
          actions.resetForm({
            values: {
              // the type of `values` inferred to be Blog
              title: '',
              image: '',
              body: '',
            },
            // you can also set the other form states here
          });
        });
      }}
    >
      // etc
    </Formik>
  );
}
```

If `nextState` is omitted, then Formik will reset state to the original initial state. The latter is useful for calling `resetForm` within `componentDidUpdate` or `useEffect`.

```tsx
actions.resetForm();
```

#### `setErrors: (fields: { [field: string]: string }) => void`

Set `errors` imperatively.

#### `setFieldError: (field: string, errorMsg: string) => void`

Set the error message of a field imperatively. `field` should match the key of
`errors` you wish to update. Useful for creating custom input error handlers.

#### `setFieldTouched: (field: string, isTouched?: boolean, shouldValidate?: boolean) => Promise<void | FormikErrors>`

Set the touched state of a field imperatively. `field` should match the key of
`touched` you wish to update. Useful for creating custom input blur handlers. Calling this method will trigger validation to run if `validateOnBlur` is set to `true` (which it is by default). `isTouched` defaults to `true` if not specified. You can also explicitly prevent/skip validation by passing a third argument as `false`.

If `validateOnBlur` is set to `true` and there are errors, they will be resolved in the returned `Promise`.

#### `submitForm: () => Promise`

Trigger a form submission. The promise will be rejected if form is invalid.

#### `submitCount: number`

Number of times user tried to submit the form. Increases when [`handleSubmit`](#handlesubmit-e-reactformeventhtmlformelement--void) is called, resets after calling
[`handleReset`](#handlereset---void). `submitCount` is readonly computed property and should not be mutated directly.

#### `setFieldValue: (field: string, value: React.SetStateAction<any>, shouldValidate?: boolean) => Promise<void | FormikErrors>`

Set the value of a field imperatively. `field` should match the key of
`values` you wish to update. Useful for creating custom input change handlers. Calling this will trigger validation to run if `validateOnChange` is set to `true` (which it is by default). You can also explicitly prevent/skip validation by passing a third argument as `false`.

If `validateOnChange` is set to `true` and there are errors, they will be resolved in the returned `Promise`.

#### `setStatus: (status?: any) => void`

Set a top-level `status` to anything you want imperatively. Useful for
controlling arbitrary top-level state related to your form. For example, you can
use it to pass API responses back into your component in `handleSubmit`.

#### `setSubmitting: (isSubmitting: boolean) => void`

Set `isSubmitting` imperatively. You would call it with `setSubmitting(false)` in your `onSubmit` handler to finish the cycle. To learn more about the submission process, see [Form Submission](../guides/form-submission.md).

#### `setTouched: (fields: { [field: string]: boolean }, shouldValidate?: boolean) => Promise<void | FormikErrors>`

Set `touched` imperatively. Calling this will trigger validation to run if `validateOnBlur` is set to `true` (which it is by default). You can also explicitly prevent/skip validation by passing a second argument as `false`.

If `validateOnBlur` is set to `true` and there are errors, they will be resolved in the returned `Promise`.

#### `setValues: (fields: React.SetStateAction<{ [field: string]: any }>, shouldValidate?: boolean) => Promise<void | FormikErrors<Values>>`

Set `values` imperatively. Calling this will trigger validation to run if `validateOnChange` is set to `true` (which it is by default). You can also explicitly prevent/skip validation by passing a second argument as `false`.

If `validateOnChange` is set to `true` and there are errors, they will be resolved in the returned `Promise`.

#### `status?: any`

A top-level status object that you can use to represent form state that can't
otherwise be expressed/stored with other methods. This is useful for capturing
and passing through API responses to your inner component.

`status` should only be modified by calling
[`setStatus`](#setstatus-status-any--void).

#### `touched: { [field: string]: boolean }`

Touched fields. Each key corresponds to a field that has been touched/visited.

#### `values: { [field: string]: any }`

Your form's values. Will have the shape of the result of `mapPropsToValues`
(if specified) or all props that are not functions passed to your wrapped
component.

#### `validateForm: (values?: any) => Promise<FormikErrors<Values>>`

Imperatively call your `validate` or `validateSchema` depending on what was specified. You can optionally pass values to validate against and this modify Formik state accordingly, otherwise this will use the current `values` of the form.

#### `validateField: (field: string) => void`

Imperatively call field's `validate` function if specified for given field or run schema validation using [Yup's `schema.validateAt`](https://github.com/jquense/yup#mixedvalidateatpath-string-value-any-options-object-promiseany-validationerror) and the provided top-level `validationSchema` prop. Formik will use the current field value.

### `component?: React.ComponentType<FormikProps<Values>>`

```jsx
<Formik component={ContactForm} />;

const ContactForm = ({
  handleSubmit,
  handleChange,
  handleBlur,
  values,
  errors,
}) => (
  <form onSubmit={handleSubmit}>
    <input
      type="text"
      onChange={handleChange}
      onBlur={handleBlur}
      value={values.name}
      name="name"
    />
    {errors.name && <div>{errors.name}</div>}
    <button type="submit">Submit</button>
  </form>
);
```

**Warning:** `<Formik component>` takes precedence over `<Formik render>` so
don’t use both in the same `<Formik>`.

### `render: (props: FormikProps<Values>) => ReactNode`

**Deprecated in 2.x**

```jsx
<Formik render={props => <ContactForm {...props} />} />

<Formik
  render={({ handleSubmit, handleChange, handleBlur, values, errors }) => (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        onChange={handleChange}
        onBlur={handleBlur}
        value={values.name}
        name="name"
      />
      {errors.name &&
        <div>
          {errors.name}
        </div>}
      <button type="submit">Submit</button>
    </form>
  )}
/>
```

### `children?: React.ReactNode | (props: FormikProps<Values>) => ReactNode`

```jsx
<Formik children={props => <ContactForm {...props} />} />

// or...

<Formik>
  {({ handleSubmit, handleChange, handleBlur, values, errors }) => (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        onChange={handleChange}
        onBlur={handleBlur}
        value={values.name}
        name="name"
      />
      {errors.name &&
        <div>
          {errors.name}
        </div>}
      <button type="submit">Submit</button>
    </form>
  )}
</Formik>
```

### `enableReinitialize?: boolean`

Default is `false`. Control whether Formik should reset the form if
`initialValues` changes (using deep equality).

### `isInitialValid?: boolean`

**Deprecated in 2.x, use `initialErrors` instead**

Control the initial value of `isValid` prop prior to
mount. You can also pass a function. Useful for situations when you want to
enable/disable a submit and reset buttons on initial mount.

### `initialErrors?: FormikErrors<Values>`

Initial field errors of the form, Formik will make these values available to
render methods component as `errors`.

Note: `initialErrors` is not available to the higher-order component `withFormik`, use
`mapPropsToErrors` instead.

### `initialStatus?: any`

An arbitrary value for the initial `status` of the form. If the form is reset, this value will be restored.

Note: `initialStatus` is not available to the higher-order component `withFormik`, use
`mapPropsToStatus` instead.

### `initialTouched?: FormikTouched<Values>`

Initial visited fields of the form, Formik will make these values available to
render methods component as `touched`.

Note: `initialTouched` is not available to the higher-order component `withFormik`, use
`mapPropsToTouched` instead.

### `initialValues: Values`

Initial field values of the form, Formik will make these values available to
render methods component as `values`.

Even if your form is empty by default, you must initialize all fields with
initial values otherwise React will throw an error saying that you have changed
an input from uncontrolled to controlled.

Note: `initialValues` not available to the higher-order component, use
`mapPropsToValues` instead.

### `onReset?: (values: Values, formikBag: FormikBag) => void`

Your optional form reset handler. It is passed your forms `values` and the
"FormikBag".

### `onSubmit: (values: Values, formikBag: FormikBag) => void | Promise<any>`

Your form submission handler. It is passed your forms `values` and the
"FormikBag", which includes an object containing a subset of the
[injected props and methods](#formik-render-methods-and-props) (i.e. all the methods
with names that start with `set<Thing>` + `resetForm`) and any props that were
passed to the wrapped component.

Note: `errors`, `touched`, `status` and all event handlers are NOT
included in the `FormikBag`.

> IMPORTANT: If `onSubmit` is async, then Formik will automatically set `isSubmitting` to `false` on your behalf once it has resolved. This means you do NOT need to call `formikBag.setSubmitting(false)` manually. However, if your `onSubmit` function is synchronous, then you need to call `setSubmitting(false)` on your own.

### `validate?: (values: Values) => FormikErrors<Values> | Promise<any>`

_Note: I suggest using `validationSchema` and Yup for validation. However,
`validate` is a dependency-free, straightforward way to validate your forms._

Validate the form's `values` with function. This function can either be:

1. Synchronous and return an `errors` object.

```js
// Synchronous validation
const validate = values => {
  const errors = {};

  if (!values.email) {
    errors.email = 'Required';
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
    errors.email = 'Invalid email address';
  }

  //...

  return errors;
};
```

- Asynchronous and return a Promise that's resolves to an object containing `errors`

```js
// Async Validation
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

const validate = values => {
  return sleep(2000).then(() => {
    const errors = {};
    if (['admin', 'null', 'god'].includes(values.username)) {
      errors.username = 'Nice try';
    }
    // ...
    return errors;
  });
};
```

### `validateOnBlur?: boolean`

Default is `true`. Use this option to run validations on `blur` events. More
specifically, when either `handleBlur`, `setFieldTouched`, or `setTouched`
are called.

### `validateOnChange?: boolean`

Default is `true`. Use this option to tell Formik to run validations on `change`
events and `change`-related methods. More specifically, when either
`handleChange`, `setFieldValue`, or `setValues` are called.

### `validateOnMount?: boolean`

Default is `false`. Use this option to tell Formik to run validations when the `<Formik />` component mounts
and/or `initialValues` change.

### `validationSchema?: Schema | (() => Schema)`

[A Yup schema](https://github.com/jquense/yup) or a function that returns a Yup
schema. This is used for validation. Errors are mapped by key to the inner
component's `errors`. Its keys should match those of `values`.


================================================
FILE: docs/api/useField.md
================================================
---
id: useField
title: useField()
---

`useField` is a React hook used to thread Formik behaviors into arbitrary field components. It provides the greatest amount of flexibility for scenarios where `Field` is inappropriate. There are two ways to use it.

## Example

```tsx
import React from 'react';
import { useField, Form, FormikProps, Formik } from 'formik';

interface Values {
  firstName: string;
  lastName: string;
  email: string;
}

const MyTextField = ({ label, ...props }) => {
  const [field, meta] = useField(props);
  return (
    <>
      <label>
        {label}
        <input {...field} {...props} />
      </label>
      {meta.touched && meta.error ? (
        <div className="error">{meta.error}</div>
      ) : null}
    </>
  );
};

const Example = () => (
  <div>
    <h1>My Form</h1>
    <Formik
      initialValues={{
        email: '',
        firstName: 'red',
        lastName: '',
      }}
      onSubmit={(values, actions) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          actions.setSubmitting(false);
        }, 1000);
      }}
    >
      {(props: FormikProps<Values>) => (
        <Form>
          <MyTextField name="firstName" type="text" label="First Name" />
          <MyTextField name="lastName" type="text" label="Last Name" />
          <MyTextField name="email" type="email" label="Email" />
          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  </div>
);
```

---

# Reference

## `useField<Value = any>(name: string | FieldHookConfig<Value>): [FieldInputProps<Value>, FieldMetaProps<Value>, FieldHelperProps]`

A custom React Hook that returns a 3-tuple (an array with three elements) containing `FieldProps`, `FieldMetaProps` and `FieldHelperProps`. It accepts either a string of a field name or an object as an argument. The object must at least contain a `name` key. This object is a subset of the props that you would pass to `<Field>` and the values and functions in `FieldProps` will mimic the behavior of `<Field>` exactly. This is useful, and generally preferred, since it allows you to take advantage of Formik's checkbox, radio, and multiple select behavior when the object contains the relevant key/values (e.g. `type: 'checkbox'`, `multiple: true`, etc.).

`FieldMetaProps` contains computed values about the field which can be used to style or otherwise change the field. `FieldHelperProps` contains helper functions that allow you to imperatively change a field's values.

```jsx
import React from 'react';
import { useField } from 'formik';

function MyTextField(props) {
  // this will return field props for an <input />
  const [field, meta, helpers] = useField(props.name);
  return (
    <>
      <input {...field} {...props} />
      {meta.error && meta.touched && <div>{meta.error}</div>}
    </>
  );
}

function MyInput(props) {
  // this will return field exactly like <Field>{({ field }) => ... }</Field>
  const [field, meta] = useField(props);
  return (
    <>
      <input {...field} {...props} />
      {meta.error && meta.touched && <div>{meta.error}</div>}
    </>
  );
}

function MyOtherComponent(props) {
  // This isn't an input, so instead of using the values in 'field' directly,
  // we'll use 'meta' and 'helpers'.
  const [field, meta, helpers] = useField(props.name);

  const { value } = meta;
  const { setValue } = helpers;

  const isSelected = v => (v === value ? 'selected' : '');

  return (
    <div className="itemsPerPage">
      <button onClick={() => setValue(5)} className={isSelected(5)}>
        5
      </button>
      <button onClick={() => setValue(10)} className={isSelected(10)}>
        10
      </button>
      <button onClick={() => setValue(25)} className={isSelected(25)}>
        25
      </button>
    </div>
  );
}
```

### `FieldHookConfig<Value>`

This object is a subset of the props that you would pass to `<Field>`. It contains:

- `name: string` - The name of the field
- `validate?: (value: any) => undefined | string | Promise<any>` - See [the documentation for `<Field>`](./field#validate)
- `type?: string` - The type of the HTML input (`text`, `number` and etc.)
- `multiple?: boolean` - Whether or not the multiple values can be selected.
- `value?: string`- Works only for inputs of type `checkbox` and `radio`. When a form is submitted, checkboxes and radios are submitted with the provided `value`. Read more about it on [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox#Value).

### `FieldInputProps<Value>`

An object that contains:

- `name: string` - The name of the field
- `checked?: boolean` - Whether or not the input is checked, this is _only_ defined if `useField` is passed an object with a `name`, `type: 'checkbox'` or `type: 'radio'`.
- `onBlur: () => void` - A blur event handler
- `onChange: (e: React.ChangeEvent<any>) => void` - A change event handler
- `value: Value` - The field's value (plucked out of `values`) or, if it is a checkbox or radio input, then potentially the `value` passed into `useField`.
- `multiple?: boolean` - Whether or not the multiple values can be selected. This is only ever defined when `useField` is passed an object with `multiple: true`

### `FieldMetaProps<Value>`

An object that contains relevant computed metadata about a field. More specifically,

- `error?: string` - The field's error message (plucked out of `errors`)
- `initialError?: string` - The field's initial error if the field is present in `initialErrors` (plucked out of `initialErrors`)
- `initialTouched: boolean` - The field's initial value if the field is present in `initialTouched` (plucked out of `initialTouched`)
- `initialValue?: Value` - The field's initial value if the field is given a value in `initialValues` (plucked out of `initialValues`)
- `touched: boolean` - Whether the field has been visited (plucked out of `touched`)
- `value: any` - The field's value (plucked out of `values`)

### `FieldHelperProps`

An object that contains helper functions which you can use to imperatively change the value, error value or touched status for the field in question. This is useful for components which need to change a field's status directly, without triggering change or blur events.

- `setValue(value: any, shouldValidate?: boolean): Promise<void | FormikErrors>` - A function to change the field's value. Calling this will trigger validation to run if `validateOnChange` is set to `true` (which it is by default). You can also explicitly prevent/skip validation by passing a second argument as `false`.
If `validateOnChange` is set to `true` and there are errors, they will be resolved in the returned `Promise`.

- `setTouched(value: boolean, shouldValidate?: boolean): void` - A function to change the field's touched status. Calling this will trigger validation to run if `validateOnBlur` is set to `true` (which it is by default). You can also explicitly prevent/skip validation by passing a second argument as `false`.
If `validateOnBlur` is set to `true` and there are errors, they will be resolved in the returned `Promise`.

- `setError(value: any): void` - A function to change the field's error value


================================================
FILE: docs/api/useFormik.md
================================================
---
id: useFormik
title: useFormik()
---

`useFormik()` is a custom React hook that will return all Formik state and helpers directly. Despite its name, it is not meant for the majority of use cases. Internally, Formik uses `useFormik` to create the `<Formik>` component (which renders a [React Context](https://reactjs.org/docs/context.html) Provider). If you are trying to access Formik state via context, use [useFormikContext](useFormikContext.md). Only use this hook if you are NOT using `<Formik>` or `withFormik`.

\*\* Be aware that `<Field>`, `<FastField>`, `<ErrorMessage>`, `connect()`, and `<FieldArray>` will NOT work with `useFormik()` as they all require React Context.

## Use cases for `useFormik()`

- You are Jared
- You are modifying the returned value and creating a modified version of `<Formik>` for your own consumption
- You want to avoid using React Context (possibly for perf reasons)

## Example

```jsx
import React from 'react';
import { useFormik } from 'formik';

const SignupForm = () => {
  const formik = useFormik({
    initialValues: {
      firstName: '',
      lastName: '',
      email: '',
    },
    onSubmit: values => {
      alert(JSON.stringify(values, null, 2));
    },
  });
  return (
    <form onSubmit={formik.handleSubmit}>
      <label htmlFor="firstName">First Name</label>
      <input
        id="firstName"
        name="firstName"
        type="text"
        onChange={formik.handleChange}
        value={formik.values.firstName}
      />
      <label htmlFor="lastName">Last Name</label>
      <input
        id="lastName"
        name="lastName"
        type="text"
        onChange={formik.handleChange}
        value={formik.values.lastName}
      />
      <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>
  );
};
```

---

# Reference

## `useFormik<Values>(config: FormikConfig<Values>): FormikProps<Values>`

A custom React Hook that returns Formik states and helpers. It is used internally to create the `<Formik>` component, but is exported for advanced use cases or for those people that do not want to use React Context.


================================================
FILE: docs/api/useFormikContext.md
================================================
---
id: useFormikContext
title: useFormikContext()
---

`useFormikContext()` is a custom React hook that will return all Formik state and helpers via [React Context](https://reactjs.org/docs/context.html).

## Example

Here's an example of a form that works similarly to Stripe's 2-factor verification form. As soon as you type a 6 digit number, the form will automatically submit (i.e. no enter keypress is needed).

```js
import React from 'react';
import { useFormikContext, Formik, Form, Field } from 'formik';

const AutoSubmitToken = () => {
  // Grab values and submitForm from context
  const { values, submitForm } = useFormikContext();
  React.useEffect(() => {
    // Submit the form imperatively as an effect as soon as form values.token are 6 digits long
    if (values.token.length === 6) {
      submitForm();
    }
  }, [values, submitForm]);
  return null;
};

const TwoFactorVerificationForm = () => (
  <div>
    <h1>2-step Verification</h1>
    <p>Please enter the 6 digit code sent to your device</p>
    <Formik
      initialValues={{ token: '' }}
      validate={values => {
        const errors = {};
        if (values.token.length < 5) {
          errors.token = 'Invalid code. Too short.';
        }
        return errors;
      }}
      onSubmit={(values, actions) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          actions.setSubmitting(false);
        }, 1000);
      }}
    >
      <Form>
        <Field name="token" type="tel" />
        <AutoSubmitToken />
      </Form>
    </Formik>
  </div>
);
```

---

# Reference

## `useFormikContext(): FormikProps<Values>`

A custom React Hook that returns Formik states and helpers via React Context. Thus, this hook will only work if there is a parent Formik React Context from which it can pull from. If called without a parent context (i.e. a descendent of a `<Formik>` component or `withFormik` higher-order component), you will get a warning in your console.


================================================
FILE: docs/api/utils.md
================================================
---
id: utils
title: Utils
---

# Reference

## Exported Functions

#### `getActiveElement(doc?: Document): Element | null`

#### `getIn(obj: any, key: string | string[], def?: any, p?: number): any`

#### `setIn(obj: any, path: string, value: any): any`

#### `setNestedObjectValues<T>(object: any, value: any, visited?: any, response?: any): T`

#### `isEmptyArray: (value?: any) => boolean`

#### `isFunction: (obj: any) => obj is Function`

#### `isObject: (obj: any) => obj is Object`

#### `isInteger: (obj: any) => boolean`

#### `isString: (obj: any) => obj is string`

#### `isNaN: (obj: any) => boolean`

#### `isEmptyChildren: (children: any) => boolean`

#### `isPromise: (value: any) => value is PromiseLike<any>`

#### `isInputEvent: (value: any) => value is React.SyntheticEvent<any, Event>`


================================================
FILE: docs/api/withFormik.md
================================================
---
id: withFormik
title: withFormik()
---

Create a higher-order React component class that passes props and form handlers
(the "`FormikBag`") into your component derived from supplied options.

## Example

```jsx
import React from 'react';
import { withFormik } from 'formik';

const MyForm = props => {
  const {
    values,
    touched,
    errors,
    handleChange,
    handleBlur,
    handleSubmit,
  } = props;
  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        onChange={handleChange}
        onBlur={handleBlur}
        value={values.name}
        name="name"
      />
      {errors.name && touched.name && <div id="feedback">{errors.name}</div>}
      <button type="submit">Submit</button>
    </form>
  );
};

const MyEnhancedForm = withFormik({
  mapPropsToValues: () => ({ name: '' }),

  // Custom sync validation
  validate: values => {
    const errors = {};

    if (!values.name) {
      errors.name = 'Required';
    }

    return errors;
  },

  handleSubmit: (values, { setSubmitting }) => {
    setTimeout(() => {
      alert(JSON.stringify(values, null, 2));
      setSubmitting(false);
    }, 1000);
  },

  displayName: 'BasicForm',
})(MyForm);
```

#### `options`

---

# Reference

## `options`

### `displayName?: string`

When your inner form component is a stateless functional component, you can use
the `displayName` option to give the component a proper name so you can more
easily find it in
[React DevTools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en).
If specified, your wrapped form will show up as `Formik(displayName)`. If
omitted, it will show up as `Formik(Component)`. This option is not required for
class components (e.g. `class XXXXX extends React.Component {..}`).

### `enableReinitialize?: boolean`

Default is `false`. Control whether Formik should reset the form if the wrapped
component props change (using deep equality).

### `handleSubmit: (values: Values, formikBag: FormikBag) => void | Promise<any>`

Your form submission handler. It is passed your forms `values` and the
"FormikBag", which includes an object containing a subset of the
[injected props and methods](#injected-props-and-methods) (i.e. all the methods
with names that start with `set<Thing>` + `resetForm`) and any props that were
passed to the wrapped component.

#### The "FormikBag"

- `props` (props passed to the wrapped component)
- `resetForm`
- `setErrors`
- `setFieldError`
- `setFieldTouched`
- `setFieldValue`
- `setStatus`
- `setSubmitting`
- `setTouched`
- `setValues`

Note: `errors`, `touched`, `status` and all event handlers are NOT
included in the `FormikBag`.

> IMPORTANT: If `onSubmit` is async, then Formik will automatically set `isSubmitting` to `false` on your behalf once it has resolved. This means you do NOT need to call `formikBag.setSubmitting(false)` manually. However, if your `onSubmit` function is synchronous, then you need to call `setSubmitting(false)` on your own.

### `isInitialValid?: boolean | (props: Props) => boolean`

**Deprecated in 2.x, use `mapPropsToErrors` instead**

Control the initial value of `isValid` prop prior to
mount. You can also pass a function. Useful for situations when you want to
enable/disable a submit and reset buttons on initial mount.

### `mapPropsToErrors?: (props: Props) => FormikErrors<Values>`

If this option is specified, then Formik will transfer its results into
updatable form state and make these values available to the new component as
`props.errors` initially. Useful for instantiating arbitrary error state into your form. As a reminder, `props.errors` will be overwritten as soon as validation runs. Formik will also reset `props.errors` to this initial value (and this function will be re-run) if the form is reset.

### `mapPropsToStatus?: (props: Props) => any`

If this option is specified, then Formik will transfer its results into
updatable form state and make these values available to the new component as
`props.status`. Useful for storing or instantiating arbitrary state into your form. As a reminder, `status` will be reset to this initial value (and this function will be re-run) if the form is reset.

### `mapPropsToTouched?: (props: Props) => FormikTouched<Values>`

If this option is specified, then Formik will transfer its results into
updatable form state and make these values available to the new component as
`props.touched`. Useful for instantiating arbitrary touched state (i.e. marking fields as visited) into your form. As a reminder, Formik will use this initial value (and this function will be re-run) if the form is reset.

### `mapPropsToValues?: (props: Props) => Values`

If this option is specified, then Formik will transfer its results into
updatable form state and make these values available to the new component as
`props.values`. If `mapPropsToValues` is not specified, then Formik
will map all props that are not functions to the inner component's
`props.values`. That is, if you omit it, Formik will only pass
`props` where `typeof props[k] !== 'function'`, where `k` is some key.

Even if your form is not receiving any props from its parent, use
`mapPropsToValues` to initialize your forms empty state.

### `validate?: (values: Values, props: Props) => FormikErrors<Values> | Promise<any>`

_Note: I suggest using `validationSchema` and Yup for validation. However,
`validate` is a dependency-free, straightforward way to validate your forms._

Validate the form's `values` with function. This function can either be:

1. Synchronous and return an `errors` object.

```js
// Synchronous validation
const validate = (values, props) => {
  const errors = {};

  if (!values.email) {
    errors.email = 'Required';
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
    errors.email = 'Invalid email address';
  }

  //...

  return errors;
};
```

- Asynchronous and return a Promise that's resolves to an object containing `errors`

```js
// Async Validation
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

const validate = (values, props) => {
  return sleep(2000).then(() => {
    const errors = {};
    if (['admin', 'null', 'god'].includes(values.username)) {
      errors.username = 'Nice try';
    }
    // ...
    return errors;
  });
};
```

### `validateOnBlur?: boolean`

Default is `true`. Use this option to run validations on `blur` events. More
specifically, when either `handleBlur`, `setFieldTouched`, or `setTouched`
are called.

### `validateOnChange?: boolean`

Default is `true`. Use this option to tell Formik to run validations on `change`
events and `change`-related methods. More specifically, when either
`handleChange`, `setFieldValue`, or `setValues` are called.

### `validateOnMount?: boolean`

Default is `false`. Use this option to tell Formik to run validation (at low priority) when the wrapped component mounts
and/or `initialValues` change.

### `validationSchema?: Schema | ((props: Props) => Schema)`

[A Yup schema](https://github.com/jquense/yup) or a function that returns a Yup
schema. This is used for validation. Errors are mapped by key to the inner
component's `errors`. Its keys should match those of `values`.

## Injected props and methods

These are identical to the props of [`<Formik render={props => ...} />`](./formik#formik-render-methods-and-props)


================================================
FILE: docs/examples/async-submission.md
================================================
---
title: Async Submission Example
description: This example demonstrates how to use async/await to submit a Formik form.
---

This example demonstrates how to use `async`/`await` to submit a Formik form.

<div className="embed-responsive aspect-ratio-square">
  <iframe
  src="https://codesandbox.io/embed/github/formik/formik/tree/main/examples/async-submission?fontsize=14&hidenavigation=1&theme=dark"
  style={{ width:'100%', height: '100%', border:0, borderRadius: 4, overflow: 'hidden'}}
  title="formik/formik: async-submission"
  allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
  sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
  ></iframe>
</div>


================================================
FILE: docs/examples/basic.md
================================================
---
title: Basic Example
description: This example demonstrates how to use Formik in its most basic way.
---

This example demonstrates how to use Formik in its most basic way.

<div className="embed-responsive aspect-ratio-square">
  <iframe
  src="https://codesandbox.io/embed/github/formik/formik/tree/main/examples/basic?fontsize=14&hidenavigation=1&theme=dark"
  style={{ width:'100%', height: '100%', border:0, borderRadius: 4, overflow: 'hidden'}}
  title="formik/formik: async-submission"
  allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
  sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
  ></iframe>
</div>


================================================
FILE: docs/examples/checkboxes.md
================================================
---
title: Checkboxes Example
description: This example demonstrates how to use Formik with a checkbox group. Given that the fields all share the same `name`, Formik will automagically bind them to a single array.
---

This example demonstrates how to use Formik with a checkbox group. Given that the fields all share the same `name`, Formik will automagically bind them to a single array.

<div className="embed-responsive aspect-ratio-square">
  <iframe
  src="https://codesandbox.io/embed/github/formik/formik/tree/main/examples/checkboxes?fontsize=14&hidenavigation=1&theme=dark"
  style={{ width:'100%', height: '100%', border:0, borderRadius: 4, overflow: 'hidden'}}
  title="formik/formik: async-submission"
  allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
  sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
  ></iframe>
</div>


================================================
FILE: docs/examples/dependent-fields-async-api-request.md
================================================
---
title: Dependent fields with an Async API Request Example
description: This is an example of a complex dependent field in Formik v2. In this example, one field's value is set by making an asynchronous API request based on the current values of other fields.
---

This is an example of a complex dependent field in Formik. In this example, one field's value is set by making an asynchronous API request based on the current values of other fields.

<div className="embed-responsive aspect-ratio-square">
  <iframe
  src="https://codesandbox.io/embed/github/formik/formik/tree/main/examples/dependent-fields-async-api-request?fontsize=14&hidenavigation=1&theme=dark"
  style={{ width:'100%', height: '100%', border:0, borderRadius: 4, overflow: 'hidden'}}
  title="formik/formik: async-submission"
  allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
  sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
  ></iframe>
</div>


================================================
FILE: docs/examples/dependent-fields.md
================================================
---
title: Dependent Fields Example
description: This is an example of how to set the value of one field based on the current values of other fields in Formik.
---

This is an example of how to set the value of one field based on the current values of other fields in Formik.

<div className="embed-responsive aspect-ratio-square">
  <iframe
  src="https://codesandbox.io/embed/github/formik/formik/tree/main/examples/dependent-fields?fontsize=14&hidenavigation=1&theme=dark"
  style={{ width:'100%', height: '100%', border:0, borderRadius: 4, overflow: 'hidden'}}
  title="formik/formik: async-submission"
  allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
  sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
  ></iframe>
</div>


================================================
FILE: docs/examples/field-arrays.md
================================================
---
title: Field Arrays Example
---

This example demonstrates how to work with array fields in Formik.

<div className="embed-responsive aspect-ratio-square">
  <iframe
  src="https://codesandbox.io/embed/github/formik/formik/tree/main/examples/field-arrays?fontsize=14&hidenavigation=1&theme=dark"
  style={{ width:'100%', height: '100%', border:0, borderRadius: 4, overflow: 'hidden'}}
  title="formik/formik: async-submission"
  allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
  sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
  ></iframe>
</div>


================================================
FILE: docs/examples/instant-feedback.md
================================================
---
title: Accessible Instant Feedback Example
---

Instant feedback during typing can be extremely helpful in certain situations. For example, checking the validity (or availability) of a username shouldn't require the user to resubmit the form (multiple times). Providing instant feedback while users are typing can allow them to experiment more easily until they find valid input value (like a suitable username). Note: This isn't always optimal, use your judgement.

<div className="embed-responsive aspect-ratio-square">
  <iframe
  src="https://codesandbox.io/embed/github/formik/formik/tree/main/examples/instant-feedback?fontsize=14&hidenavigation=1&theme=dark"
  style={{ width:'100%', height: '100%', border:0, borderRadius: 4, overflow: 'hidden'}}
  title="formik/formik: async-submission"
  allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
  sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
  ></iframe>
</div>


================================================
FILE: docs/examples/more-examples.md
================================================
---
title: More Examples
---

You can find additional examples in [`examples` folder of the Formik GitHub repository](https://github.com/formik/formik/tree/main/examples/).


================================================
FILE: docs/examples/radio-group.md
================================================
---
title: Radio Group Example
description: This example demonstrates how to create a radio group with Formik.
---

This example demonstrates how to create a radio group with Formik.

<div className="embed-responsive aspect-ratio-square">
  <iframe
  src="https://codesandbox.io/embed/github/formik/formik/tree/main/examples/radio-group?fontsize=14&hidenavigation=1&theme=dark"
  style={{ width:'100%', height: '100%', border:0, borderRadius: 4, overflow: 'hidden'}}
  title="formik/formik: async-submission"
  allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
  sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
  ></iframe>
</div>


================================================
FILE: docs/examples/typescript.md
================================================
---
title: Basic TypeScript
description: This example demonstrates how to use Formik in its most basic way with TypeScript.
---

This example demonstrates how to use Formik in its most basic way with TypeScript.

<div className="embed-responsive aspect-ratio-square">
  <iframe
  src="https://codesandbox.io/embed/github/formik/formik/tree/main/examples/basic-typescript?fontsize=14&hidenavigation=1&theme=dark"
  style={{ width:'100%', height: '100%', border:0, borderRadius: 4, overflow: 'hidden'}}
  title="formik/formik: async-submission"
  allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
  sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
  ></iframe>
</div>


================================================
FILE: docs/examples/with-material-ui.md
================================================
---
id: with-material-ui
title: Material UI
---

Formik can be easily used/integrated with [Material UI](https://material-ui.com/), with just passing a few formik props to the respective Material UI Component props. Refer to the example below to get started.

<div className="embed-responsive aspect-ratio-square">
  <iframe
  src="https://codesandbox.io/embed/github/formik/formik/tree/main/examples/with-material-ui?fontsize=14&hidenavigation=1&theme=dark"
  style={{ width:'100%', height: '100%', border:0, borderRadius: 4, overflow: 'hidden'}}
  title="formik/formik: async-submission"
  allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
  sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
  ></iframe>
</div>


================================================
FILE: docs/examples.md
================================================
---
id: examples
title: Examples
description: Runnable examples of using Formik in React and React Native to create forms
---

## Dependent Fields

Programmatically set the value of one field based on the current values of other fields.

https://codesandbox.io/s/formik-v2x-dependent-fields-r0n0v

## Dependent Fields based on Async API Request

In this example, one field's value is set by making an async API based on the current values of two other fields.

https://codesandbox.io/s/formik-v2x-dependent-field-with-async-api-request-4yjrv


================================================
FILE: docs/guides/arrays.md
================================================
---
id: arrays
title: Arrays and Nested Objects
---

Formik has support for nested objects and arrays out of the box. These subjects are somewhat related because they both leverage the same syntax.

## Nested Objects

The `name` props in Formik can use lodash-like dot paths to reference nested Formik values. This means that you do not need to flatten out your form's values anymore.

```jsx
import React from 'react';
import { Formik, Form, Field } from 'formik';

export const NestedExample = () => (
  <div>
    <h1>Social Profiles</h1>
    <Formik
      initialValues={{
        social: {
          facebook: '',
          twitter: '',
        },
      }}
      onSubmit={values => {
        // same shape as initial values
        console.log(values);
      }}
    >
      <Form>
        <Field name="social.facebook" />
        <Field name="social.twitter" />
        <button type="submit">Submit</button>
      </Form>
    </Formik>
  </div>
);
```

## Arrays

Formik also has support for arrays and arrays of objects out of the box. Using lodash-like bracket syntax for `name` string you can quickly build fields for items in a list.

```jsx
import React from 'react';
import { Formik, Form, Field } from 'formik';

export const BasicArrayExample = () => (
  <div>
    <h1>Friends</h1>
    <Formik
      initialValues={{
        friends: ['jared', 'ian'],
      }}
      onSubmit={values => {
        // same shape as initial values
        console.log(values);
      }}
    >
      <Form>
        <Field name="friends[0]" />
        <Field name="friends[1]" />
        <button type="submit">Submit</button>
      </Form>
    </Formik>
  </div>
);
```

For more information around manipulating (add/remove/etc) items in lists, see the API reference section on the `<FieldArray>` component.

## Avoid nesting

If you want to avoid this default behavior Formik also has support for it to have fields with dots.

```jsx
import React from 'react';
import { Formik, Form, Field } from 'formik';

export const NestedExample = () => (
  <div>
    <h1>Social Profiles</h1>
    <Formik
      initialValues={{
        'owner.fullname': '',
      }}
      onSubmit={values => {
        // same shape as initial values
        console.log(values);
      }}
    >
      <Form>
        <Field name="['owner.fullname']" />
        <button type="submit">Submit</button>
      </Form>
    </Formik>
  </div>
);
```


================================================
FILE: docs/guides/form-submission.md
================================================
---
id: form-submission
title: Form Submission
---

## Submission Phases

To submit a form in Formik, you need to somehow fire off the provided `handleSubmit(e)` or `submitForm` prop. When you call either of these methods, Formik will execute the following _(pseudo code)_ each time:

### Pre-submit

- Touch all fields. `initialValues` are required and should always be specified. See [#445](https://github.com/jaredpalmer/formik/issues/445#issuecomment-366952762)
- Set `isSubmitting` to `true`
- Increment `submitCount` + 1

### Validation

- Set `isValidating` to `true`
- Run all field-level validations, `validate`, and `validationSchema` asynchronously and deeply merge results
- Are there any errors?
  - Yes: Abort submission. Set `isValidating` to `false`, set `errors`, set `isSubmitting` to `false`
  - No: Set `isValidating` to `false`, proceed to "Submission"

### Submission

- Proceed with running the submission handler (i.e. `onSubmit` or `handleSubmit`)
- Did the submit handler return a promise?
  - Yes: Wait until it is resolved or rejected, then set `setSubmitting` to `false`
  - No: _Call `setSubmitting(false)`_ to finish the cycle

## Frequently Asked Questions

<details>
<summary>How do I determine if my submission handler is executing?</summary>

If `isValidating` is `false` and `isSubmitting` is `true`.

</details>

<details>
<summary>Why does Formik touch all fields before submit?</summary>

It is common practice to only show an input's errors in the UI if it has been visited (a.k.a "touched"). Before submitting a form, Formik touches all fields so that all errors that may have been hidden will now be visible.

</details>

<details>
<summary>How do I protect against double submits?</summary>

Disable whatever is triggering submission if `isSubmitting` is `true`.

</details>

<details>
<summary>How do I know when my form is validating before submit?</summary>

If `isValidating` is `true` and `isSubmitting` is `true`.

</details>

<details>
<summary>Why does `isSubmitting` remain true after submission?</summary>
  
If the submission handler returns a promise, make sure it is correctly resolved or rejected when called.

If the submission handler does not return a promise, make sure `setSubmitting(false)` is called at the end of the handler.

</details>


================================================
FILE: docs/guides/react-native.md
================================================
---
id: react-native
title: React Native
---

**Formik is 100% compatible with React Native and React Native Web.** However,
because of differences between ReactDOM's and React Native's handling of forms
and text input, there are some differences to be aware of. This section will walk
you through them and what we consider to be best practices.

### The gist

Before going any further, here's a super minimal gist of how to use Formik with
React Native that demonstrates the key differences:

```jsx
// Formik x React Native example
import React from 'react';
import { Button, TextInput, View } from 'react-native';
import { Formik } from 'formik';

export const MyReactNativeForm = props => (
  <Formik
    initialValues={{ email: '' }}
    onSubmit={values => console.log(values)}
  >
    {({ handleChange, handleBlur, handleSubmit, values }) => (
      <View>
        <TextInput
          onChangeText={handleChange('email')}
          onBlur={handleBlur('email')}
          value={values.email}
        />
        <Button onPress={handleSubmit} title="Submit" />
      </View>
    )}
  </Formik>
);
```

As you can see above, the notable differences between using Formik with React
DOM and React Native are:

1. Formik's `handleSubmit` is passed to a `<Button onPress={...} />`
   instead of HTML `<form onSubmit={...} />` component (since there is no
   `<form />` element in React Native).
2. `<TextInput />` uses Formik's `handleChange(fieldName)` and `handleBlur(fieldName)` instead of directly assigning the callbacks to props, because we have to get the `fieldName` from somewhere and with React Native we can't get it automatically like in web (using input name attribute). You can also use `setFieldValue(fieldName, value)` and `setFieldTouched(fieldName, bool)` as an alternative.


================================================
FILE: docs/guides/typescript.md
================================================
---
id: typescript
title: TypeScript
---

The Formik source code is written in TypeScript, so you can rest easy that Formik's
types will always be up-to-date. As a mental model, Formik's type signatures are very
similar to React Router 4's `<Route>`.

#### Render props (`<Formik />` and `<Field />`)

```typescript
import * as React from 'react';
import {
  Formik,
  FormikHelpers,
  FormikProps,
  Form,
  Field,
  FieldProps,
} from 'formik';

interface MyFormValues {
  firstName: string;
}

export const MyApp: React.FC<{}> = () => {
  const initialValues: MyFormValues = { firstName: '' };
  return (
    <div>
      <h1>My Example</h1>
      <Formik
        initialValues={initialValues}
        onSubmit={(values, actions) => {
          console.log({ values, actions });
          alert(JSON.stringify(values, null, 2));
          actions.setSubmitting(false);
        }}
      >
        <Form>
          <label htmlFor="firstName">First Name</label>
          <Field id="firstName" name="firstName" placeholder="First Name" />
          <button type="submit">Submit</button>
        </Form>
      </Formik>
    </div>
  );
};
```

#### `withFormik()`

```tsx
import React from 'react';
import * as Yup from 'yup';
import { withFormik, FormikProps, FormikErrors, Form, Field } from 'formik';

// Shape of form values
interface FormValues {
  email: string;
  password: string;
}

interface OtherProps {
  message: string;
}

// Aside: You may see InjectedFormikProps<OtherProps, FormValues> instead of what comes below in older code.. InjectedFormikProps was artifact of when Formik only exported a HoC. It is also less flexible as it MUST wrap all props (it passes them through).
const InnerForm = (props: OtherProps & FormikProps<FormValues>) => {
  const { touched, errors, isSubmitting, message } = props;
  return (
    <Form>
      <h1>{message}</h1>
      <Field type="email" name="email" />
      {touched.email && errors.email && <div>{errors.email}</div>}

      <Field type="password" name="password" />
      {touched.password && errors.password && <div>{errors.password}</div>}

      <button type="submit" disabled={isSubmitting}>
        Submit
      </button>
    </Form>
  );
};

// The type of props MyForm receives
interface MyFormProps {
  initialEmail?: string;
  message: string; // if this passed all the way through you might do this or make a union type
}

// Wrap our form with the withFormik HoC
const MyForm = withFormik<MyFormProps, FormValues>({
  // Transform outer props into form values
  mapPropsToValues: props => {
    return {
      email: props.initialEmail || '',
      password: '',
    };
  },

  // Add a custom validation function (this can be async too!)
  validate: (values: FormValues) => {
    let errors: FormikErrors<FormValues> = {};
    if (!values.email) {
      errors.email = 'Required';
    } else if (!isValidEmail(values.email)) {
      errors.email = 'Invalid email address';
    }
    return errors;
  },

  handleSubmit: values => {
    // do submitting things
  },
})(InnerForm);

// Use <MyForm /> wherevs
const Basic = () => (
  <div>
    <h1>My App</h1>
    <p>This can be anywhere in your application</p>
    <MyForm message="Sign up" />
  </div>
);

export default Basic;
```


================================================
FILE: docs/guides/validation.md
================================================
---
id: validation
title: Validation
---

Formik is designed to manage forms with complex validation with ease. Formik supports synchronous and asynchronous
form-level and field-level validation. Furthermore, it comes with baked-in support for schema-based form-level validation through Yup. This guide will describe the ins and outs of all of the above.

## Flavors of Validation

### Form-level Validation

Form-level validation is useful because you have complete access to all of your form's `values` and props whenever the function runs, so you can validate dependent fields at the same time.

There are 2 ways to do form-level validation with Formik:

- `<Formik validate>` and `withFormik({ validate: ... })`
- `<Formik validationSchema>` and `withFormik({ validationSchema: ... })`

#### `validate`

`<Formik>` and `withFormik()` take a prop/option called `validate` that accepts either a synchronous or asynchronous function.

```js
// Synchronous validation
const validate = (values, props /* only available when using withFormik */) => {
  const errors = {};

  if (!values.email) {
    errors.email = 'Required';
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
    errors.email = 'Invalid email address';
  }

  //...

  return errors;
};

// Async Validation
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

const validate = (values, props /* only available when using withFormik */) => {
  return sleep(2000).then(() => {
    const errors = {};
    if (['admin', 'null', 'god'].includes(values.username)) {
      errors.username = 'Nice try';
    }
    // ...
    return errors;
  });
};
```

For more information about `<Formik validate>`, see the API reference.

#### `validationSchema`

As you can see above, validation is left up to you. Feel free to write your own
validators or use a 3rd party library. At The Palmer Group, we use
[Yup](https://github.com/jquense/yup) for object schema validation. It has an
API that's pretty similar to [Joi](https://github.com/hapijs/joi) and
[React PropTypes](https://github.com/facebook/prop-types) but is small enough
for the browser and fast enough for runtime usage. Because we ❤️ Yup sooo
much, Formik has a special config option / prop for Yup object schemas called `validationSchema` which will automatically transform Yup's validation errors into a pretty object whose keys match `values` and `touched`. This symmetry makes it easy to manage business logic around error messages.

To add Yup to your project, install it from NPM.

```sh
npm install yup --save
```

```jsx
import React from 'react';
import { Formik, Form, Field } from 'formik';
import * as Yup from 'yup';

const SignupSchema = Yup.object().shape({
  firstName: Yup.string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required('Required'),
  lastName: Yup.string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required('Required'),
  email: Yup.string().email('Invalid email').required('Required'),
});

export const ValidationSchemaExample = () => (
  <div>
    <h1>Signup</h1>
    <Formik
      initialValues={{
        firstName: '',
        lastName: '',
        email: '',
      }}
      validationSchema={SignupSchema}
      onSubmit={values => {
        // same shape as initial values
        console.log(values);
      }}
    >
      {({ errors, touched }) => (
        <Form>
          <Field name="firstName" />
          {errors.firstName && touched.firstName ? (
            <div>{errors.firstName}</div>
          ) : null}
          <Field name="lastName" />
          {errors.lastName && touched.lastName ? (
            <div>{errors.lastName}</div>
          ) : null}
          <Field name="email" type="email" />
          {errors.email && touched.email ? <div>{errors.email}</div> : null}
          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  </div>
);
```

For more information about `<Formik validationSchema>`, see the API reference.

### Field-level Validation

#### `validate`

Formik supports field-level validation via the `validate` prop of `<Field>`/`<FastField>` components or `useField` hook. This function can be synchronous or asynchronous (return a Promise). It will run after any `onChange` and `onBlur` by default. This behavior can be altered at the top level `<Formik/>` component using the `validateOnChange` and `validateOnBlur` props respectively. In addition to change/blur, all field-level validations are run at the beginning of a submission attempt and then the results are deeply merged with any top-level validation results.

> Note: The `<Field>/<FastField>` components' `validate` function will only be executed on mounted fields. That is to say, if any of your fields unmount during the flow of your form (e.g. Material-UI's `<Tabs>` unmounts the previous `<Tab>` your user was on), those fields will not be validated during form validation/submission.

```jsx
import React from 'react';
import { Formik, Form, Field } from 'formik';

function validateEmail(value) {
  let error;
  if (!value) {
    error = 'Required';
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)) {
    error = 'Invalid email address';
  }
  return error;
}

function validateUsername(value) {
  let error;
  if (value === 'admin') {
    error = 'Nice try!';
  }
  return error;
}

export const FieldLevelValidationExample = () => (
  <div>
    <h1>Signup</h1>
    <Formik
      initialValues={{
        username: '',
        email: '',
      }}
      onSubmit={values => {
        // same shape as initial values
        console.log(values);
      }}
    >
      {({ errors, touched, isValidating }) => (
        <Form>
          <Field name="email" validate={validateEmail} />
          {errors.email && touched.email && <div>{errors.email}</div>}

          <Field name="username" validate={validateUsername} />
          {errors.username && touched.username && <div>{errors.username}</div>}

          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  </div>
);
```

### Manually Triggering Validation

You can manually trigger both form-level and field-level validation with Formik using the `validateForm` and `validateField` methods respectively.

```jsx
import React from 'react';
import { Formik, Form, Field } from 'formik';

function validateEmail(value) {
  let error;
  if (!value) {
    error = 'Required';
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)) {
    error = 'Invalid email address';
  }
  return error;
}

function validateUsername(value) {
  let error;
  if (value === 'admin') {
    error = 'Nice try!';
  }
  return error;
}

export const FieldLevelValidationExample = () => (
  <div>
    <h1>Signup</h1>
    <Formik
      initialValues={{
        username: '',
        email: '',
      }}
      onSubmit={values => {
        // same shape as initial values
        console.log(values);
      }}
    >
      {({ errors, touched, validateField, validateForm }) => (
        <Form>
          <Field name="email" validate={validateEmail} />
          {errors.email && touched.email && <div>{errors.email}</div>}

          <Field name="username" validate={validateUsername} />
          {errors.username && touched.username && <div>{errors.username}</div>}
          {/** Trigger field-level validation
           imperatively */}
          <button type="button" onClick={() => validateField('username')}>
            Check Username
          </button>
          {/** Trigger form-level validation
           imperatively */}
          <button
            type="button"
            onClick={() => validateForm().then(() => console.log('blah'))}
          >
            Validate All
          </button>
          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  </div>
);
```

## When Does Validation Run?

You can control when Formik runs validation by changing the values of `<Formik validateOnChange>` and/or `<Formik validateOnBlur>` props depending on your needs. By default, Formik will run validation methods as follows:

**After "change" events/methods** (things that update`values`)

- `handleChange`
- `setFieldValue`
- `setValues`

**After "blur" events/methods** (things that update `touched`)

- `handleBlur`
- `setTouched`
- `setFieldTouched`

**Whenever submission is attempted**

- `handleSubmit`
- `submitForm`

There are also imperative helper methods provided to you via Formik's render/injected props which you can use to imperatively call validation.

- `validateForm`
- `validateField`

## Displaying Error Messages

Error messages are dependent on the form's validation. If an error exists, and the validation function produces an error object (as it should) with a matching shape to our values/initialValues, dependent field errors can be accessed from the errors object.

```js
import React from 'react';
import { Formik, Form, Field } from 'formik';
import * as Yup from 'yup';

const DisplayingErrorMessagesSchema = Yup.object().shape({
  username: Yup.string()
    .min(2, 'Too Short!')
    .max(50, 'Too Long!')
    .required('Required'),
  email: Yup.string().email('Invalid email').required('Required'),
});

export const DisplayingErrorMessagesExample = () => (
  <div>
    <h1>Displaying Error Messages</h1>
    <Formik
      initialValues={{
        username: '',
        email: '',
      }}
      validationSchema={DisplayingErrorMessagesSchema}
      onSubmit={values => {
        // same shape as initial values
        console.log(values);
      }}
    >
      {({ errors, touched }) => (
        <Form>
          <Field name="username" />
          {/* If this field has been touched, and it contains an error, display it
           */}
          {touched.username && errors.username && <div>{errors.username}</div>}
          <Field name="email" />
          {/* If this field has been touched, and it contains an error, display
          it */}
          {touched.email && errors.email && <div>{errors.email}</div>}
          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  </div>
);
```

> The [ErrorMessage](../api/errormessage.md) component can also be used to display error messages.

## Frequently Asked Questions

<details>
<summary>How do I determine if my form is validating?</summary>

If `isValidating` prop is `true`

</details>

<details>
<summary>Can I return `null` as an error message?</summary>

No. Use `undefined` instead. Formik uses `undefined` to represent empty states. If you use `null`, several parts of Formik's computed props (e.g. `isValid` for example), will not work as expected.

</details>

<details>
<summary>How do I test validation?</summary>

Formik has extensive unit tests for Yup validation so you do not need to test that. However, if you are rolling your own validation functions, you should simply unit test those. If you do need to test Formik's execution you should use the imperative `validateForm` and `validateField` methods respectively.

</details>


================================================
FILE: docs/manifest.json
================================================
{
  "routes": [
    {
      "title": "Documentation",
      "heading": true,
      "routes": [
        {
          "title": "Getting Started",
          "path": "/docs/overview.md"
        },
        {
          "title": "Tutorial",
          "path": "/docs/tutorial.md"
        },
        {
          "title": "Resources",
          "path": "/docs/resources.md"
        },
        {
          "title": "3rd-Party Bindings",
          "path": "/docs/3rd-party-bindings.md"
        },
        {
          "title": "Migrating from v1.x to v2.x",
          "path": "/docs/migrating-v2.md"
        },
        {
          "title": "Guides",
          "open": true,
          "routes": [
            {
              "title": "Validation",
              "path": "/docs/guides/validation.md"
            },
            {
              "title": "Arrays",
              "path": "/docs/guides/arrays.md"
            },
            {
              "title": "TypeScript",
              "path": "/docs/guides/typescript.md"
            },
            {
              "title": "React Native",
              "path": "/docs/guides/react-native.md"
            },
            {
              "title": "Form Submission",
              "path": "/docs/guides/form-submission.md"
            }
          ]
        },
        {
          "title": "Examples",
          "open": true,
          "routes": [
            {
              "title": "Basic",
              "path": "/docs/examples/basic.md"
            },
            {
              "title": "TypeScript",
              "path": "/docs/examples/typescript.md"
            },
            {
              "title": "Async Submission",
              "path": "/docs/examples/async-submission.md"
            },

            {
              "title": "Checkboxes",
              "path": "/docs/examples/checkboxes.md"
            },
            {
              "title": "Radio Group",
              "path": "/docs/examples/radio-group.md"
            },
            {
              "title": "Dependent Fields",
              "path": "/docs/examples/dependent-fields.md"
            },
            {
              "title": "Dependent Fields with Async API Request",
              "path": "/docs/examples/dependent-fields-async-api-request.md"
            },
            {
              "title": "Arrays and Lists",
              "path": "/docs/examples/field-arrays.md"
            },
            {
              "title": "Instant Feedback",
              "path": "/docs/examples/instant-feedback.md"
            },
            {
              "title": "Material UI",
              "path": "/docs/examples/with-material-ui.md"
            },
            {
              "title": "More Examples",
              "path": "/docs/examples/more-examples.md"
            }
          ]
        }
      ]
    },

    {
      "title": "API Reference",
      "heading": true,
      "routes": [
        {
          "title": "connect()",
          "path": "/docs/api/connect.md"
        },
        {
          "title": "<ErrorMessage />",
          "path": "/docs/api/errormessage.md"
        },
        {
          "title": "<FastField />",
          "path": "/docs/api/fastfield.md"
        },
        {
          "title": "<Field />",
          "path": "/docs/api/field.md"
        },
        {
          "title": "<FieldArray />",
          "path": "/docs/api/fieldarray.md"
        },
        {
          "title": "<Form />",
          "path": "/docs/api/form.md"
        },
        {
          "title": "<Formik />",
          "path": "/docs/api/formik.md"
        },
        {
          "title": "useField()",
          "path": "/docs/api/useField.md"
        },
        {
          "title": "useFormik()",
          "path": "/docs/api/useFormik.md"
        },
        {
          "title": "useFormikContext()",
          "path": "/docs/api/useFormikContext.md"
        },
        {
          "title": "withFormik()",
          "path": "/docs/api/withFormik.md"
        }
      ]
    }
  ]
}


================================================
FILE: docs/migrating-v2.md
================================================
---
id: migrating-v2
title: Migrating from v1.x to v2.x
description: How to migrate from Formik v1 to v2
---

## Breaking Changes

### Minimum Requirements

- Since Formik 2 is built on top of React Hooks, you must be on React 16.8.x or higher
- Since Formik 2 uses the `unknown` type, you must be on TypeScript 3.0 or higher (if you use TypeScript)

**There are a few breaking changes in Formik 2.x.** Luckily, these probably won't impact many people:

### `resetForm`

With Formik 2, we introduced the new props for more initial state: `initialErrors`, `initialTouched`, `initialStatus`. Therefore, `resetForm`'s signature has changed. Instead of optionally accepting just the next initial values of the form. It now optionally accepts the partial next initial state of Formik.

**v1**

```jsx
// Reset to `initialValues`
formik.resetForm();
// Reset form and set the next `initialValues` of the form
formik.resetForm({ name: '', email: '' });
```

**v2**

```jsx
// Reset the form. This will set the next initial state of
// Formik to the `initialValues`, `initialErrors`, `initialTouched`,
// `initialStatus` props.
formik.resetForm();

// Reset the form back to `initialXXXX` but change next
// `initialValues` to a custom value
formik.resetForm({
  values: { name: 'Custom initial values', email: '' },
});

// Reset form back to `initialXXXX`, but change next `initialValues`
// and `initialErrors` of the form
formik.resetForm({
  values: { name: '', email: '' },
  errors: { name: 'Something special' },
});

// Reset form back to `initialXXXX`, but change next `initialStatus` to 'Foo'
formik.resetForm({
  status: 'Foo',
});
```

### `setError`

This method has been deprecated for a while with a warning in v1.x releases. It's fully removed in v2. Please use Formik's `setStatus(status)` instead. It works identically. Note: this is/was not `setErrors` (plural) which is still around.

### `validate`

As you may know, you can return a Promise of a validation error from `validate`. In 1.x, it didn't matter if this promise is resolved or rejected as in both cases the payload of the promise was interpreted as the validation error. In 2.x, rejection will be interpreted as an actual exception and it won't update the form error state. Any validation function that returns a rejected promise of errors needs to be adjusted to return a resolved promise of errors instead.

### `ref`

Currently, you can't attach a ref to Formik using the `ref` prop. However, you still can get around this issue using the prop `innerRef`. We have some WIP [#2208](https://github.com/jaredpalmer/formik/issues/2208) to instead use `React.forwardRef`.

### `isValid`

This property does not take the value of `dirty` into account anymore. This means that if you want to disable a submit button when the form is not `dirty` (i.e. on first render and when values are unchanged), you have to explicitly check for it.

```tsx
<button disabled={!isValid || !dirty} type="submit">
  Submit
</button>
```

### Typescript changes

#### `FormikActions`

**`FormikActions` has been renamed to `FormikHelpers`** It should be a straightforward change to import or alias the type

**v1**

```tsx
import { FormikActions } from 'formik';
```

**v2**

```tsx
import { FormikHelpers as FormikActions } from 'formik';
```

#### `FieldProps`

**`FieldProps` now accepts two generic type parameters.** Both parameters are optional, but `FormValues` has been moved from the first to the second parameter.

**v1**

```tsx
type Props = FieldProps<FormValues>;
```

**v2**

```tsx
type Props = FieldProps<FieldValue, FormValues>;
```

## What's New?

### Checkboxes and Select multiple

Similarly to Angular, Vue, or Svelte, Formik 2 "fixes" React checkboxes and multi-selects with built-in array binding and boolean behavior. This was one of the most confusing things for people in Formik 1.x.

```jsx
import React from 'react';
import { Formik, Field, Form } from 'formik';
import { Debug } from './Debug';

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

const CheckboxExample = () => (
  <div>
    <h1>Checkboxes</h1>
    <p>
      This example demonstrates how to properly create checkboxes with Formik.
    </p>
    <Formik
      initialValues={{
        isAwesome: false,
        terms: false,
        newsletter: false,
        jobType: ['designer'],
        location: [],
      }}
      onSubmit={async values => {
        await sleep(1000);
        alert(JSON.stringify(values, null, 2));
      }}
    >
      {({ isSubmitting, getFieldProps, handleChange, handleBlur, values }) => (
        <Form>
          {/* 
            This first checkbox will result in a boolean value being stored.
          */}
          <div className="label">Basic Info</div>
          <label>
            <Field type="checkbox" name="isAwesome" />
            Are you awesome?
          </label>
          {/* 
            Multiple checkboxes with the same name attribute, but different
            value attributes will be considered a "checkbox group". Formik will automagically
            bind the checked values to a single array for your benefit. All the add and remove
            logic will be taken care of for you.
          */}
          <div className="label">
            What best describes you? (check all that apply)
          </div>
          <label>
            <Field type="checkbox" name="jobType" value="designer" />
            Designer
          </label>
          <label>
            <Field type="checkbox" name="jobType" value="developer" />
            Developer
          </label>
          <label>
            <Field type="checkbox" name="jobType" value="product" />
            Product Manager
          </label>
          {/*
           You do not _need_ to use <Field>/useField to get this behavior, 
           using handleChange, handleBlur, and values works as well. 
          */}
          <label>
            <input
              type="checkbox"
              name="jobType"
              value="founder"
              checked={values.jobType.includes('founder')}
              onChange={handleChange}
              onBlur={handleBlur}
            />
            CEO / Founder
          </label>

          {/* 
           The <select> element will also behave the same way if 
           you pass `multiple` prop to it. 
          */}
          <label htmlFor="location">Where do you work?</label>
          <Field
            component="select"
            id="location"
            name="location"
            multiple={true}
          >
            <option value="NY">New York</option>
            <option value="SF">San Francisco</option>
            <option value="CH">Chicago</option>
            <option value="OTHER">Other</option>
          </Field>
          <label>
            <Field type="checkbox" name="terms" />I accept the terms and
            conditions.
          </label>
          {/* Here's how you can use a checkbox to show / hide another field */}
          {!!values.terms ? (
            <div>
              <label>
                <Field type="checkbox" name="newsletter" />
                Send me the newsletter <em style={{ color: 'rebeccapurple' }}>
                  (This is only shown if terms = true)
                </em>
              </label>
            </div>
          ) : null}
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
          <Debug />
        </Form>
      )}
    </Formik>
  </div>
);

export default CheckboxExample;
```

### `useField()`

Just what you think, it's like `<Field>`, but with a hook. See docs for usage.

### `useFormikContext()`

A hook that is equivalent to `connect()`.

### `<Field as>`

`<Field/>` now accepts a prop called `as` which will inject `onChange`, `onBlur`, `value` etc. directly through to the component or string. This is useful for folks using Emotion or Styled components as they no longer need to clean up `component`'s render props in a wrapped function.

```jsx
// <input className="form-input" placeholder="Jane"  />
<Field name="firstName" className="form-input" placeholder="Jane" />

// <textarea className="form-textarea"/></textarea>
<Field name="message" as="textarea"  className="form-textarea"/>

// <select className="my-select"/>
<Field name="colors" as="select" className="my-select">
  <option value="red">Red</option>
  <option value="green">Green</option>
  <option value="blue">Blue</option>
</Field>

// with styled-components/emotion
const MyStyledInput = styled.input`
  padding: .5em;
  border: 1px solid #eee;
  /* ... */
`
const MyStyledTextarea = MyStyledInput.withComponent('textarea');

// <input className="czx_123" placeholder="google.com"  />
<Field name="website" as={MyStyledInput} placeholder="google.com"/>

// <textarea placeholder="Post a message..." rows={5}></textarea>
<Field name="message" as={MyStyledTextArea} placeholder="Post a message.." rows={4}/>
```

### `getFieldProps(nameOrProps)`

There are two useful additions to `FormikProps`, `getFieldProps` and `getFieldMeta`. These are Kent C. Dodds-esque prop getters that can be useful if you love prop drilling, are _not_ using the context-based API's, or if you are building a custom `useField`.

```tsx
export interface FieldInputProps<Value> {
  /** Value of the field */
  value: Value;
  /** Name of the field */
  name: string;
  /** Multiple select? */
  multiple?: boolean;
  /** Is the field checked? */
  checked?: boolean;
  /** Change event handler */
  onChange: FormikHandlers['handleChange'];
  /** Blur event handler */
  onBlur: FormikHandlers['handleBlur'];
}
```

### `getFieldMeta(name)`

Given a name it will return an object:

```tsx
export interface FieldMetaProps<Value> {
  /** Value of the field */
  value: Value;
  /** Error message of the field */
  error?: string;
  /** Has the field been visited? */
  touched: boolean;
  /** Initial value of the field */
  initialValue?: Value;
  /** Initial touched state of the field */
  initialTouched: boolean;
  /** Initial error message of the field */
  initialError?: string;
}
```

### Misc

- `FormikContext` is now exported
- `validateOnMount?: boolean = false`
- `initialErrors`, `initialTouched`, `initialStatus` have been added

## Deprecation Warnings

### All `render` props have been deprecated with a console warning.

For `<Field>`, `<FastField>`, `<Formik>`,`<FieldArray>`, the `render` prop has been deprecated with a warning as it will be removed in future versions. Instead, use a child callback function. This deprecation is meant to parallel React Context Consumer's usage.

```diff
- <Field name="firstName" render={props => ....} />
+ <Field name="firstName">{props => ... }</Field>
```


================================================
FILE: docs/overview.md
================================================
---
id: overview
title: Overview
description: Formik documentation, tutorial, guides, and examples
---

Let's face it, forms are really verbose in
[React](https://github.com/facebook/react). To make matters worse, most form
helpers do wayyyy too much magic and often have a significant performance cost
associated with them. Formik is a small library that helps you with the 3 most
annoying parts:

1.  Getting values in and out of form state
2.  Validation and error messages
3.  Handling form submission

By colocating all of the above in one place, Formik will keep things
organized--making testing, refactoring, and reasoning about your forms a breeze.

## Motivation

I ([@jaredpalmer](https://twitter.com/jaredpalmer)) wrote Formik while building a large internal administrative dashboard with
[@eonwhite](https://twitter.com/eonwhite). With around ~30 unique forms, it
quickly became obvious that we could benefit by standardizing not just our input
components but also the way in which data flowed through our forms.

### Why not Redux-Form?

By now, you might be thinking, "Why didn't you just use
[Redux-Form](https://github.com/erikras/redux-form)?" Good question.

1.  According to our prophet Dan Abramov,
    [**form state is inherently ephemeral and local**, so tracking it in Redux (or any kind of Flux library) is unnecessary](https://github.com/reactjs/redux/issues/1287#issuecomment-175351978)
2.  Redux-Form calls your entire top-level Redux reducer multiple times ON EVERY
    SINGLE KEYSTROKE. This is fine for small apps, but as your Redux app grows,
    input latency will continue to increase if you use Redux-Form.
3.  Redux-Form is 22.5 kB minified gzipped (Formik is 12.7 kB)

**My goal with Formik was to create a scalable, performant, form helper with a
minimal API that does the really really annoying stuff, and leaves the rest up
to you.**

---

My talk at React Alicante goes much deeper into Formik's motivation and philosophy, introduces the library (by watching me build a mini version of it), and demos how to build a non-trivial form (with arrays, custom inputs, etc.) using the real thing.

<div className="embed-responsive aspect-ratio-16-9">
  <iframe className="embed-responsive-item" width="600" height="315" src="https://www.youtube.com/embed/oiNtnehlaTo" frameBorder="0" allow="autoplay; encrypted-media" allowFullScreen title="Taming Forms in React - Jared Palmer"></iframe>
</div>

## Influences

Formik started by expanding on
[this little higher order component](https://github.com/jxnblk/rebass-recomposed/blob/master/src/withForm.js)
by [Brent Jackson](https://github.com/jxnblk), some naming conventions from
Redux-Form, and (most recently) the render props approach popularized by
[React-Motion](https://github.com/chenglou/react-motion) and
[React-Router 4](https://github.com/ReactTraining/react-router). Whether you
have used any of the above or not, Formik only takes a few minutes to get
started with.

## Installation

You can install Formik with [NPM](https://npmjs.com),
[Yarn](https://yarnpkg.com), or a good ol' `<script>` via
[unpkg.com](https://unpkg.com).

### NPM

```sh
npm install formik --save
```

or

```sh
yarn add formik
```

Formik is compatible with React v15+ and works with ReactDOM and React Native.

You can also try before you buy with this
**[demo of Formik on CodeSandbox.io](https://codesandbox.io/s/zKrK5YLDZ)**

### In-browser Playgrounds

You can play with Formik in your web browser with these live online playgrounds.

- [CodeSandbox (ReactDOM)](https://codesandbox.io/s/zKrK5YLDZ)
- [Snack (React Native)](https://snack.expo.io/?dependencies=yup%2Cformik%2Creact-native-paper%2Cexpo-constants&sourceUrl=https%3A%2F%2Fgist.githubusercontent.com%2Fbrentvatne%2F700e1dbf9c3e88a11aef8e557627ce3f%2Fraw%2Feeee57721c9890c1212ac34a4c37707f6354f469%2FApp.js)

## The Gist

Formik keeps track of your form's state and then exposes it plus a few reusable
methods and event handlers (`handleChange`, `handleBlur`, and `handleSubmit`) to
your form via `props`. `handleChange` and `handleBlur` work exactly as
expected--they use a `name` or `id` attribute to figure out which field to
update.

```jsx
import React from 'react';
import { Formik } from 'formik';

const Basic = () => (
  <div>
    <h1>Anywhere in your app!</h1>
    <Formik
      initialValues={{ email: '', password: '' }}
      validate={values => {
        const errors = {};
        if (!values.email) {
          errors.email = 'Required';
        } else if (
          !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)
        ) {
          errors.email = 'Invalid email address';
        }
        return errors;
      }}
      onSubmit={(values, { setSubmitting }) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          setSubmitting(false);
        }, 400);
      }}
    >
      {({
        values,
        errors,
        touched,
        handleChange,
        handleBlur,
        handleSubmit,
        isSubmitting,
        /* and other goodies */
      }) => (
        <form onSubmit={handleSubmit}>
          <input
            type="email"
            name="email"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.email}
          />
          {errors.email && touched.email && errors.email}
          <input
            type="password"
            name="password"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.password}
          />
          {errors.password && touched.password && errors.password}
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </form>
      )}
    </Formik>
  </div>
);

export default Basic;
```

### Reducing boilerplate

The code above is very explicit about exactly what Formik is doing. `onChange` -> `handleChange`, `onBlur` -> `handleBlur`, and so on. However, to save you time, Formik comes with a few extra components to make life easier and less verbose: `<Form />`, `<Field />`, and `<ErrorMessage />`. They use React context to hook into the parent `<Formik />` state/methods.

```jsx
// Render Prop
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';

const Basic = () => (
  <div>
    <h1>Any place in your app!</h1>
    <Formik
      initialValues={{ email: '', password: '' }}
      validate={values => {
        const errors = {};
        if (!values.email) {
          errors.email = 'Required';
        } else if (
          !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)
        ) {
          errors.email = 'Invalid email address';
        }
        return errors;
      }}
      onSubmit={(values, { setSubmitting }) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          setSubmitting(false);
        }, 400);
      }}
    >
      {({ isSubmitting }) => (
        <Form>
          <Field type="email" name="email" />
          <ErrorMessage name="email" component="div" />
          <Field type="password" name="password" />
          <ErrorMessage name="password" component="div" />
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </Form>
      )}
    </Formik>
  </div>
);

export default Basic;
```

Read below for more information...

### Complementary Packages

As you can see above, validation is left up to you. Feel free to write your own
validators or use a 3rd party library. Personally, I use
[Yup](https://github.com/jquense/yup) for object schema validation. It has an
API that's pretty similar to [Joi](https://github.com/hapijs/joi) /
[React PropTypes](https://github.com/facebook/prop-types) but is small enough
for the browser and fast enough for runtime usage. Because I ❤️ Yup sooo
much, Formik has a special config option / prop for Yup called
[`validationSchema`](./api/formik.md#validationschema-schema----schema) which will
automatically transform Yup's validation errors into a pretty object whose keys
match [`values`](./api/formik.md#values-field-string-any) and
[`touched`](./api/formik.md#touched-field-string-boolean). Anyways, you can
install Yup from npm...

```
npm install yup --save
```

or

```
yarn add yup
```


================================================
FILE: docs/resources.md
================================================
---
id: resources
title: Resources
description: Formik conference talks, courses, videos, blog posts, learning resources.
---

## Conference Talks

- [Taming Forms in React](https://jaredpalmer.com/blog/formik-taming-forms-in-react) by
  [Jared Palmer](https://twitter.com/jaredpalmer) @ React Alicante - Sep 15, 2018
- [An Introduction to Formik](https://youtu.be/-tDy7ds0dag?t=33s) by
  [Jared Palmer](https://twitter.com/jaredpalmer) @ Spotify NYC - Aug 15, 2017

## Community Videos

- [Build and Validate Forms in React Native with Formik & Yup](https://www.reactnativeschool.com/build-and-validate-forms-with-formik-and-yup) (Series) by [Spencer Carli](https://twitter.com/spencer_carli) - December 14, 2018
- [Form handling in React-Native with Formik and Yup](https://www.youtube.com/watch?v=EO08ydCCsOQ) by [Emanuel Quimper](https://twitter.com/QuimperEmanuel) - May 23, 2018
- Building an Airbnb Clone Series by [Ben Awad](https://twitter.com/benawad)
  - [Coding React Form with Formik and Ant Design - Part 3](https://www.youtube.com/watch?v=pbCrDBQFU_A&index=5&list=PLN3n1USn4xlnfJIQBa6bBjjiECnk6zL6s)
  - [Form Validation in Formik with Yup - Part 4](https://www.youtube.com/watch?v=2CBnRDJ--aM&index=6&list=PLN3n1USn4xlnfJIQBa6bBjjiECnk6zL6s)
  - [Simplifying a React form with the Formik Field Component - Part 6](https://www.youtube.com/watch?v=eMjju1nQ1F8)
  - [How to use Formik with React Native - Part 17](https://www.youtube.com/watch?v=sBWtPEinWGA)
  - [Multi Step Form in React with Formik - Part 36](https://www.youtube.com/watch?v=kKpoAhugjUc)
  - [Custom Formik Fields and Fix Typescript Imports - Part 37](https://www.youtube.com/watch?v=Xwjg8meOglI)
  - [Update Listing Form - Part 67](https://www.youtube.com/watch?v=PWgGkWwwHiE&index=69&list=PLN3n1USn4xlnfJIQBa6bBjjiECnk6zL6s)
- [Better React Forms with Formik](https://www.youtube.com/watch?v=yNiJkjEwmpw) by [Andrew Mead](https://twitter.com/andrew_j_mead) - Nov 28, 2017
- [Simple React Form with Formik](https://youtu.be/MuwQdUoNKzg) by [Ben Awad](https://twitter.com/benawad) - Nov 3, 2017
- [Building an Add Channel Form with Formik](https://www.youtube.com/watch?v=anwo_i0wgNo) by [Ben Awad](https://twitter.com/benawad) - Oct 27, 2017

## Community Articles / Tutorials

- [Managing list of form fields with formik by creating Todo App](https://dev.to/mrmuhammadali/managing-list-of-form-fields-with-formik-through-example-7o5) by [Muhammad Ali](https://twitter.com/muhammadali_io) - Dec 31, 2019
- [Accessible Formik forms](https://dev.to/ptrin/accessible-formik-forms-2gld) by [Perry Trinier](https://twitter.com/ptrin) - Oct 16, 2019
- [Building dynamic forms with Formik with React and TypeScript](https://scottdj92.ghost.io/building-dynamic-forms-with-formik-with-react-and-typescript/) by [Scott Jones](https://twitter.com/sdj2964) - Sep 1, 2018
- [Simple React form validation with Formik, Yup and/or Spected](https://itnext.io/simple-react-form-validation-with-formik-yup-and-or-spected-206ebe9e7dcc) by [Jakub Kočí](https://github.com/jakubkoci) - May 21, 2018
- [ Formik —Handling files and reCaptcha](https://hackernoon.com/formik-handling-files-and-recaptcha-209cbeae10bc) by [João Miguel Cunha](https://twitter.com/lokuzt) - Dec 18, 2017
- [Better React Forms with Formik](https://mead.io/formik/?utm_source=github&utm_campaign=formikrepo) by [Andrew Mead](https://twitter.com/andrew_j_mead) - Nov 28, 2017
- [The Joy of Forms with React and Formik](https://keyholesoftware.com/2017/10/23/the-joy-of-forms-with-react-and-formik/) by [Mat Warger](https://twitter.com/mwarger) - Oct 23, 2017
- [Painless React Forms with Formik](https://hackernoon.com/painless-react-forms-with-formik-e61b70473c60) by [João Miguel Cunha](https://twitter.com/lokuzt) - Sep 8, 2017
- [Using Formik to Handle Forms in React](https://css-tricks.com/using-formik-to-handle-forms-in-react) by [Adebiyi Adedotun](https://twitter.com/AdebiyiAL) - Apr 28, 2020


================================================
FILE: docs/tutorial.md
================================================
---
id: tutorial
title: Tutorial
description: Learn how to build forms in React with Formik.
---

## Before we start

Welcome to the Formik tutorial. This will teach you everything you need to know to build simple and complex forms in React.

If you’re impatient and just want to start hacking on your machine locally, check out [the 60-second quickstart](./overview#installation).

### What are we building?

In this tutorial, we’ll build a complex newsletter signup form with React and Formik.

You can see what we’ll be building here: [Final Result](https://codesandbox.io/s/formik-v2-tutorial-final-ge1pt). If the code doesn’t make sense to you, don’t worry! The goal of this tutorial is to help you understand Formik.

### Prerequisites

You’ll need to have familiarity with HTML, CSS, [modern JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript), and [React](https://reactjs.org) (and [React Hooks](https://reactjs.org/docs/hooks-intro.html)) to fully understand Formik and how it works. In this tutorial, we’re using [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), [let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let), [const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const), [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax), [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), [computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names), and [async/await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) . You can use the [Babel REPL](https://babeljs.io/repl/#?presets=react&code_lz=MYewdgzgLgBApgGzgWzmWBeGAeAFgRgD4AJRBEAGhgHcQAnBAEwEJsB6AwgbgChRJY_KAEMAlmDh0YWRiGABXVOgB0AczhQAokiVQAQgE8AkowAUAcjogQUcwEpeAJTjDgUACIB5ALLK6aRklTRBQ0KCohMQk6Bx4gA) to check what ES6 code compiles to.

## Setup for the Tutorial

There are two ways to complete this tutorial: you can either write the code in your browser, or you can set up a local development environment on your computer.

### Setup Option 1: Write Code in the Browser

This is the quickest way to get started!

First, open this [Starter Code](https://codesandbox.io/s/formik-v2-tutorial-start-s04yr) in a new tab. The new tab should display an email address input, a submit button, and some React code. We’ll be editing the React code in this tutorial.

Skip the second setup option, and go to the [Overview](#overview-what-is-formik) section to get an overview of Formik.

### Setup Option 2: Local Development Environment

This is completely optional and not required for this tutorial!

<details>

<summary><b>Optional: Instructions for following along locally using your preferred text editor</b></summary>

This setup requires more work, but allows you to complete the tutorial using an editor of your choice. Here are the steps to follow:

1. Make sure you have a recent version of [Node.js](https://nodejs.org/en/) installed.
1. Follow the [installation instructions for Create React App](https://create-react-app.dev) to make a new project.

```bash
npx create-react-app my-app
```

1. Install Formik

```bash
npm i formik
```

Or

```bash
yarn add formik
```

1. Delete all files in the `src/` folder of the new project

> Note:
>
> **Don’t delete the entire `src` folder, just the original source files inside it.** We’ll replace the default source files with examples for this project in the next step.

```bash
cd my-app
cd src

# If you’re using a Mac or Linux:
rm -f *

# Or, if you’re on Windows:
del *

# Then, switch back to the project folder
cd ..
```

5. Add a file named `styles.css` in the `src/` folder with [this CSS code](https://codesandbox.io/s/formik-v2-tutorial-start-s04yr?file=/src/styles.css).

6. Add a file named `index.js` in the `src/` folder with [this JS code](https://codesandbox.io/s/formik-v2-tutorial-start-s04yr?file=/src/index.js:0-759).

Now run `npm start` in the project folder and open `http://localhost:3000` in the browser. You should see an email input and a submit button.

We recommend following [these instructions](https://babeljs.io/docs/editors/) to configure syntax highlighting for your editor.

</details>

### Help, I’m Stuck!

If you get stuck, check out Formik’s [GitHub Discussions](https://github.com/formik/formik/discussions). In addition, the [Formium Community Discord Server](https://discord.gg/pJSg287) is a great way to get help quickly too. If you don’t receive an answer, or if you remain stuck, please file an issue, and we’ll help you out.

## Overview: What is Formik?

Formik is a small group of React components and hooks for building forms in React and React Native. It helps with the three most annoying parts:

1.  Getting values in and out of form state
2.  Validation and error messages
3.  Handling form submission

By colocating all of the above in one place, Formik keeps things
organized--making testing, refactoring, and reasoning about your forms a breeze.

## The Basics

We’re going to start with the _most verbose_ way of using Formik. While this may seem a bit long-winded, it’s important to see how Formik builds on itself so you have a full grasp of what’s possible and a complete mental model of how it works.

### A simple newsletter signup form

Imagine we want to add a newsletter signup form for a blog. To start, our form will have just one field named `email`. With Formik, this is just a few lines of code.

```jsx
import React from 'react';
import { useFormik } from 'formik';

const SignupForm = () => {
  // Pass the useFormik() hook initial form values and a submit function that will
  // 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>
  );
};
```

We pass our form’s `initialValues` and a submission function (`onSubmit`) to the `useFormik()` hook. The hook then returns to us a goodie bag of form state and helper methods in a variable we call `formik`. For now, the only helper methods we care about are as follows:

- `handleSubmit`: A submission handler
- `handleChange`: A change handler to pass to each `<input>`, `<select>`, or `<textarea>`
- `values`: Our form’s current values

As you can see above, we pass each of these to their respective props...and that’s it! We can now have a working form powered by Formik. Instead of managing our form’s values on our own and writing our own custom event handlers for every single input, we can just use `useFormik()`.

This is pretty neat, but with just one single input, the benefits of using `useFormik()` are unclear. So let’s add two more inputs: one for the user’s first and last name, which we’ll store as `firstName` and `lastName` in the form.

```jsx
import React from 'react';
import { useFormik } from 'formik';

const SignupForm = () => {
  // Note that we have to initialize ALL of fields with values. These
  // could come from props, but since we don’t want to prefill this form,
  // we just use an empty string. If we don’t do this, React will yell
  // at us.
  const formik = useFormik({
    initialValues: {
      firstName: '',
      lastName: '',
      email: '',
    },
    onSubmit: values => {
      alert(JSON.stringify(values, null, 2));
    },
  });
  return (
    <form onSubmit={formik.handleSubmit}>
      <label htmlFor="firstName">First Name</label>
      <input
        id="firstName"
        name="firstName"
        type="text"
        onChange={formik.handleChange}
        value={formik.values.firstName}
      />

      <label htmlFor="lastName">Last Name</label>
      <input
        id="lastName"
        name="lastName"
        type="text"
        onChange={formik.handleChange}
        value={formik.values.lastName}
      />

      <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>
  );
};
```

If you look carefully at our new code, you’ll notice some patterns and symmetry _forming_.

1. We reuse the same exact change handler function `handleChange` for each HTML input
2. We pass an `id` and `name` HTML attribute that _matches_ the property we defined in `initialValues`
3. We access the field’s value using the same name (`email` -> `formik.values.email`)

If you’re familiar with building forms with plain React, you can think of Formik’s `handleChange` as working like this:

```jsx
const [values, setValues] = React.useState({});

const handleChange = event => {
  setValues(prevValues => ({
    ...prevValues,
    // we use the name to tell Formik which key of `values` to update
    [event.target.name]: event.target.value
  });
}
```

## Validation

While our contact form works, it’s not quite feature-complete; users can submit it, but it doesn’t tell them which (if any) fields are required.

If we’re okay with using the browser’s built-in HTML input validation, we could add a `required` prop to each of our inputs, specify minimum/maximum lengths (`maxlength` and `minlength`), and/or add a `pattern` prop for regex validation for each of these inputs. These are great if we can get away with them. However, HTML validation has its limitations. First, it only works in the browser! So this clearly is not viable for React Native. Second, it’s hard/impossible to show custom error messages to our user. Third, it’s very janky.

As mentioned earlier, Formik keeps track of not only your form’s `values`, but also its validation and error messages. To add validation with JS, let’s specify a custom validation function and pass it as `validate` to the `useFormik()` hook. If an error exists, this custom validation function should produce an `error` object with a matching shape to our `values`/`initialValues`. Again..._symmetry_...yes...

```jsx
import React from 'react';
import { useFormik } from 'formik';

// A custom validation function. This must return an object
// which keys are symmetrical to our values/initialValues
const validate = values => {
  const errors = {};
  if (!values.firstName) {
    errors.firstName = 'Required';
  } else if (values.firstName.length > 15) {
    errors.firstName = 'Must be 15 characters or less';
  }

  if (!values.lastName) {
    errors.lastName = 'Required';
  } else if (values.lastName.length > 20) {
    errors.lastName = 'Must be 20 characters or less';
  }

  if (!values.email) {
    errors.email = 'Required';
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
    errors.email = 'Invalid email address';
  }

  return errors;
};

const SignupForm = () => {
  // Pass the useFormik() hook initial form values, a validate function that will be called when
  // form values change or fields are blurred, and a submit function that will
  // be called when the form is submitted
  const formik = useFormik({
    initialValues: {
      firstName: '',
      lastName: '',
      email: '',
    },
    validate,
    onSubmit: values => {
      alert(JSON.stringify(values, null, 2));
    },
  });
  return (
    <form onSubmit={formik.handleSubmit}>
      <label htmlFor="firstName">First Name</label>
      <input
        id="firstName"
        name="firstName"
        type="text"
        onChange={formik.handleChange}
        value={formik.values.firstName}
      />
      {formik.errors.firstName ? <div>{formik.errors.firstName}</div> : null}

      <label htmlFor="lastName">Last Name</label>
      <input
        id="lastName"
        name="lastName"
        type="text"
        onChange={formik.handleChange}
        value={formik.values.lastName}
      />
      {formik.errors.lastName ? <div>{formik.errors.lastName}</div> : null}

      <label htmlFor="email">Email Address</label>
      <input
        id="email"
        name="email"
        type="email"
        onChange={formik.handleChange}
        value={formik.values.email}
      />
      {formik.errors.email ? <div>{formik.errors.email}</div> : null}

      <button type="submit">Submit</button>
    </form>
  );
};
```

`formik.errors` is populated via the custom validation function. By default, Formik will validate after each keystroke (change event), each input’s [blur event](https://developer.mozilla.org/en-US/docs/Web/API/Element/blur_event), as well as prior to submission. The `onSubmit` function we passed to `useFormik()` will be executed only if there are no errors (i.e. if our `validate` function returns `{}`).

## Visited fields

While our form works, and our users see each error, it’s not a great user experience for them. Since our validation function runs on each keystroke against the _entire_ form’s `values`, our `errors` object contains _all_ validation errors at any given moment. In our component, we’re just checking if an error exists and then immediately showing it to the user. This is awkward since we’re going to show error messages for fields that the user hasn’t even visited yet. Most of the time, we only want to show a field’s error message _after_ our user is done typing in that field.

Like `errors` and `values`, Formik keeps track of which fields have been visited. It stores this information in an object called `touched` that also mirrors the shape of `values`/`initialValues`. The keys of `touched` are the field names, and the values of `touched` are booleans `true`/`false`.

To take advantage of `touched`, we pass `formik.handleBlur` to each input’s `onBlur` prop. This function works similarly to `formik.handleChange` in that it uses the `name` attribute to figure out which field to update.

```jsx
import React from 'react';
import { useFormik } from 'formik';

const validate = values => {
  const errors = {};

  if (!values.firstName) {
    errors.firstName = 'Required';
  } else if (values.firstName.length > 15) {
    errors.firstName = 'Must be 15 characters or less';
  }

  if (!values.lastName) {
    errors.lastName = 'Required';
  } else if (values.lastName.length > 20) {
    errors.lastName = 'Must be 20 characters or less';
  }

  if (!values.email) {
    errors.email = 'Required';
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
    errors.email = 'Invalid email address';
  }

  return errors;
};

const SignupForm = () => {
  const formik = useFormik({
    initialValues: {
      firstName: '',
      lastName: '',
      email: '',
    },
    validate,
    onSubmit: values => {
      alert(JSON.stringify(values, null, 2));
    },
  });
  return (
    <form onSubmit={formik.handleSubmit}>
      <label htmlFor="firstName">First Name</label>
      <input
        id="firstName"
        name="firstName"
        type="text"
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        value={formik.values.firstName}
      />
      {formik.errors.firstName ? <div>{formik.errors.firstName}</div> : null}

      <label htmlFor="lastName">Last Name</label>
      <input
        id="lastName"
        name="lastName"
        type="text"
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        value={formik.values.lastName}
      />
      {formik.errors.lastName ? <div>{formik.errors.lastName}</div> : null}

      <label htmlFor="email">Email Address</label>
      <input
        id="email"
        name="email"
        type="email"
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        value={formik.values.email}
      />
      {formik.errors.email ? <div>{formik.errors.email}</div> : null}

      <button type="submit">Submit</button>
    </form>
  );
};
```

Almost there! Now that we’re tracking `touched`, we can now change our error message render logic to _only_ show a given field’s error message if it exists _and_ if our user has visited that field.

```jsx
import React from 'react';
import { useFormik } from 'formik';

const validate = values => {
  const errors = {};

  if (!values.firstName) {
    errors.firstName = 'Required';
  } else if (values.firstName.length > 15) {
    errors.firstName = 'Must be 15 characters or less';
  }

  if (!values.lastName) {
    errors.lastName = 'Required';
  } else if (values.lastName.length > 20) {
    errors.lastName = 'Must be 20 characters or less';
  }

  if (!values.email) {
    errors.email = 'Required';
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
    errors.email = 'Invalid email address';
  }

  return errors;
};

const SignupForm = () => {
  const formik = useFormik({
    initialValues: {
      firstName: '',
      lastName: '',
      email: '',
    },
    validate,
    onSubmit: values => {
      alert(JSON.stringify(values, null, 2));
    },
  });
  return (
    <form onSubmit={formik.handleSubmit}>
      <label htmlFor="firstName">First Name</label>
      <input
        id="firstName"
        name="firstName"
        type="text"
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        value={formik.values.firstName}
      />
      {formik.touched.firstName && formik.errors.firstName ? (
        <div>{formik.errors.firstName}</div>
      ) : null}

      <label htmlFor="lastName">Last Name</label>
      <input
        id="lastName"
        name="lastName"
        type="text"
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        value={formik.values.lastName}
      />
      {formik.touched.lastName && formik.errors.lastName ? (
        <div>{formik.errors.lastName}</div>
      ) : null}

      <label htmlFor="email">Email Address</label>
      <input
        id="email"
        name="email"
        type="email"
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        value={formik.values.email}
      />
      {formik.touched.email && formik.errors.email ? (
        <div>{formik.errors.email}</div>
      ) : null}

      <button type="submit">Submit</button>
    </form>
  );
};
```

### Schema Validation with Yup

As you can see above, validation is left up to you. Feel free to write your own validators or use a 3rd-party helper library. Formik’s authors/a large portion of its users use [Jason Quense](https://github.com/jquense)’s library [Yup](https://github.com/jquense/yup) for object schema validation. Yup has an API that’s similar to [Joi](https://github.com/hapijs/joi) and [React PropTypes](https://github.com/facebook/prop-types), but is also small enough for the browser and fast enough for runtime usage. You can try it out here with this [REPL](https://runkit.com/jquense/yup).

Since Formik authors/users _love_ Yup so much, Formik has a special configuration prop for Yup called `validationSchema` which will automatically transform Yup’s validation errors messages into a pretty object whose keys match `values`/`initialValues`/`touched` (just like any custom validation function would have to). Anyways, you can install Yup from NPM/yarn like so...

```bash
npm install yup --save

# or via yarn

yarn add yup
```

To see how Yup works, let’s get rid of our custom validation function `validate` and re-write our validation with Yup and `validationSchema`:

```jsx
import React from 'react';
import { useFormik } from 'formik';
import * as Yup from 'yup';

const SignupForm = () => {
  const formik = useFormik({
    initialValues: {
      firstName: '',
      lastName: '',
      email: '',
    },
    validationSchema: Yup.object({
      firstName: Yup.string()
        .max(15, 'Must be 15 characters or less')
        .required('Required'),
      lastName: Yup.string()
        .max(20, 'Must be 20 characters or less')
        .required('Required'),
      email: Yup.string().email('Invalid email address').required('Required'),
    }),
    onSubmit: values => {
      alert(JSON.stringify(values, null, 2));
    },
  });
  return (
    <form onSubmit={formik.handleSubmit}>
      <label htmlFor="firstName">First Name</label>
      <input
        id="firstName"
        name="firstName"
        type="text"
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        value={formik.values.firstName}
      />
      {formik.touched.firstName && formik.errors.firstName ? (
        <div>{formik.errors.firstName}</div>
      ) : null}

      <label htmlFor="lastName">Last Name</label>
      <input
        id="lastName"
        name="lastName"
        type="text"
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        value={formik.values.lastName}
      />
      {formik.touched.lastName && formik.errors.lastName ? (
        <div>{formik.errors.lastName}</div>
      ) : null}

      <label htmlFor="email">Email Address</label>
      <input
        id="email"
        name="email"
        type="email"
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        value={formik.values.email}
      />
      {formik.touched.email && formik.errors.email ? (
        <div>{formik.errors.email}</div>
      ) : null}

      <button type="submit">Submit</button>
    </form>
  );
};
```

Again, Yup is 100% optional. However, we suggest giving it a try. As you can see above, we expressed the exact same validation function with just 10 lines of code instead of 30. One of Formik’s core design principles is to help you stay organized. Yup definitely helps a lot with this--schemas are extremely expressive, intuitive (since they mirror your values), and reusable. Whether or not you use Yup, we highly recommended you share commonly used validation methods across your application. This will ensure that common fields (e.g. email, street addresses, usernames, phone numbers, etc.) are validated consistently and result in a better user experience.

## Reducing Boilerplate

### `getFieldProps()`

The code above is very explicit about exactly what Formik is doing. `onChange` -> `handleChange`, `onBlur` -> `handleBlur`, and so on. However, to save you time, `useFormik()` returns a helper method called `formik.getFieldProps()` to make it faster to wire up inputs. Given some field-level info, it returns to you the exact group of `onChange`, `onBlur`, `value`, `checked` for a given field. You can then spread that on an `input`, `select`, or `textarea`.

```jsx
import React from 'react';
import { useFormik } from 'formik';
import * as Yup from 'yup';

const SignupForm = () => {
  const formik = useFormik({
    initialValues: {
      firstName: '',
      lastName: '',
      email: '',
    },
    validationSchema: Yup.object({
      firstName: Yup.string()
        .max(15, 'Must be 15 characters or less')
        .required('Required'),
      lastName: Yup.string()
        .max(20, 'Must be 20 characters or less')
        .required('Required'),
      email: Yup.string().email('Invalid email address
Download .txt
gitextract_fwjymvec/

├── .all-contributorsrc
├── .changeset/
│   ├── README.md
│   └── config.json
├── .codesandbox/
│   └── ci.json
├── .eslintrc.js
├── .github/
│   ├── CODEOWNERS
│   ├── CODE_OF_CONDUCT.md
│   ├── CONTRIBUTING.md
│   ├── FUNDING.yml
│   ├── ISSUE_TEMPLATE/
│   │   ├── 1.Bug-report.md
│   │   ├── 2.Feature-request.md
│   │   └── config.yml
│   └── workflows/
│       ├── ci.yml
│       ├── release.yml
│       └── stale.yml
├── .gitignore
├── .kodiak.toml
├── .nvmrc
├── .prettierrc
├── .vscode/
│   └── settings.json
├── LICENSE
├── SECURITY.md
├── app/
│   ├── .gitignore
│   ├── README.md
│   ├── next-env.d.ts
│   ├── package.json
│   ├── pages/
│   │   ├── _app.js
│   │   ├── basic.js
│   │   ├── index.tsx
│   │   └── sign-in.js
│   ├── styles/
│   │   └── globals.css
│   └── tsconfig.json
├── docs/
│   ├── 3rd-party-bindings.md
│   ├── api/
│   │   ├── connect.md
│   │   ├── errormessage.md
│   │   ├── fastfield.md
│   │   ├── field.md
│   │   ├── fieldarray.md
│   │   ├── form.md
│   │   ├── formik.md
│   │   ├── useField.md
│   │   ├── useFormik.md
│   │   ├── useFormikContext.md
│   │   ├── utils.md
│   │   └── withFormik.md
│   ├── examples/
│   │   ├── async-submission.md
│   │   ├── basic.md
│   │   ├── checkboxes.md
│   │   ├── dependent-fields-async-api-request.md
│   │   ├── dependent-fields.md
│   │   ├── field-arrays.md
│   │   ├── instant-feedback.md
│   │   ├── more-examples.md
│   │   ├── radio-group.md
│   │   ├── typescript.md
│   │   └── with-material-ui.md
│   ├── examples.md
│   ├── guides/
│   │   ├── arrays.md
│   │   ├── form-submission.md
│   │   ├── react-native.md
│   │   ├── typescript.md
│   │   └── validation.md
│   ├── manifest.json
│   ├── migrating-v2.md
│   ├── overview.md
│   ├── resources.md
│   └── tutorial.md
├── e2e/
│   └── basic.test.ts
├── examples/
│   ├── AsyncValidation.js
│   ├── CombinedValidations.js
│   ├── CustomInputs.js
│   ├── DebouncedAutoSave.js
│   ├── Debug.js
│   ├── ErrorMessage.js
│   ├── FastField.js
│   ├── MultistepWizard.js
│   ├── RoutedMultistepWizard.js
│   ├── RoutedMultistepWizard2.js
│   ├── SchemaValidation.js
│   ├── SyncValidation.js
│   ├── ValidateFieldWithSchema.js
│   ├── async-submission/
│   │   ├── README.md
│   │   ├── index.js
│   │   └── package.json
│   ├── basic/
│   │   ├── README.md
│   │   ├── index.js
│   │   └── package.json
│   ├── basic-typescript/
│   │   ├── README.md
│   │   ├── index.html
│   │   ├── index.tsx
│   │   ├── package.json
│   │   └── tsconfig.json
│   ├── checkboxes/
│   │   ├── README.md
│   │   ├── index.js
│   │   └── package.json
│   ├── dependent-fields/
│   │   ├── README.md
│   │   ├── index.js
│   │   ├── package.json
│   │   └── styles.css
│   ├── dependent-fields-async-api-request/
│   │   ├── README.md
│   │   ├── index.js
│   │   ├── package.json
│   │   └── styles.css
│   ├── field-arrays/
│   │   ├── README.md
│   │   ├── index.js
│   │   └── package.json
│   ├── field-level-validation/
│   │   ├── README.md
│   │   ├── index.js
│   │   └── package.json
│   ├── instant-feedback/
│   │   ├── README.md
│   │   ├── index.js
│   │   ├── package.json
│   │   └── styles.css
│   ├── radio-group/
│   │   ├── README.md
│   │   ├── index.js
│   │   └── package.json
│   ├── with-material-ui/
│   │   ├── README.md
│   │   ├── index.js
│   │   └── package.json
│   └── withFormik.js
├── package.json
├── packages/
│   ├── formik/
│   │   ├── .gitignore
│   │   ├── CHANGELOG.md
│   │   ├── MIGRATING-v2.md
│   │   ├── README.md
│   │   ├── package.json
│   │   ├── src/
│   │   │   ├── ErrorMessage.tsx
│   │   │   ├── FastField.tsx
│   │   │   ├── Field.tsx
│   │   │   ├── FieldArray.tsx
│   │   │   ├── Form.tsx
│   │   │   ├── Formik.tsx
│   │   │   ├── FormikContext.tsx
│   │   │   ├── connect.tsx
│   │   │   ├── index.tsx
│   │   │   ├── types.tsx
│   │   │   ├── utils.ts
│   │   │   └── withFormik.tsx
│   │   ├── test/
│   │   │   ├── ErrorMessage.test.tsx
│   │   │   ├── Field.test.tsx
│   │   │   ├── FieldArray.test.tsx
│   │   │   ├── Formik.test.tsx
│   │   │   ├── setupTests.ts
│   │   │   ├── testHelpers.ts
│   │   │   ├── tsconfig.json
│   │   │   ├── types.test.tsx
│   │   │   ├── utils.test.tsx
│   │   │   ├── withFormik.test.tsx
│   │   │   └── yupHelpers.test.ts
│   │   ├── tsconfig.build.json
│   │   └── types/
│   │       ├── global.d.ts
│   │       └── index.d.ts
│   └── formik-native/
│       ├── .gitignore
│       ├── CHANGELOG.md
│       ├── CONTRIBUTING.md
│       ├── README.md
│       ├── package.json
│       ├── src/
│       │   └── index.ts
│       ├── test/
│       │   └── blah.test.ts
│       └── tsconfig.build.json
├── playwright.config.ts
├── scripts/
│   ├── benchmark.tsx
│   ├── btag.sh
│   └── retag.sh
├── tsconfig.base.json
├── tsconfig.json
├── turbo.json
├── website/
│   ├── .eslintignore
│   ├── .eslintrc
│   ├── .gitignore
│   ├── .prettierignore
│   ├── README.md
│   ├── next-env.d.ts
│   ├── next.config.js
│   ├── package.json
│   ├── postcss.config.js
│   ├── public/
│   │   └── robots.txt
│   ├── scripts/
│   │   └── build-sitemap.js
│   ├── src/
│   │   ├── blog/
│   │   │   ├── formik-3-alpha.md
│   │   │   └── new-docs.md
│   │   ├── components/
│   │   │   ├── ArrowRight.tsx
│   │   │   ├── Banner.tsx
│   │   │   ├── Container.tsx
│   │   │   ├── DocsPageFooter.tsx
│   │   │   ├── ExternalLink.tsx
│   │   │   ├── Footer.tsx
│   │   │   ├── FormiumLogo.tsx
│   │   │   ├── Highlight2.tsx
│   │   │   ├── LayoutDocs.tsx
│   │   │   ├── Logo.tsx
│   │   │   ├── MDXComponents.tsx
│   │   │   ├── Nav.tsx
│   │   │   ├── ReactionForm.tsx
│   │   │   ├── Search.tsx
│   │   │   ├── Seo.tsx
│   │   │   ├── Sidebar.tsx
│   │   │   ├── SidebarCategory.tsx
│   │   │   ├── SidebarHeading.tsx
│   │   │   ├── SidebarMobile.tsx
│   │   │   ├── SidebarNavLink.tsx
│   │   │   ├── SidebarPost.tsx
│   │   │   ├── Sticky.tsx
│   │   │   ├── TWButton.tsx
│   │   │   ├── Toc.module.css
│   │   │   ├── Toc.tsx
│   │   │   ├── addRouterEvents.tsx
│   │   │   ├── clients/
│   │   │   │   ├── Client.tsx
│   │   │   │   ├── ClientsMarquee.tsx
│   │   │   │   └── Filters.tsx
│   │   │   ├── forwardRefWithAs.tsx
│   │   │   ├── markdown.module.css
│   │   │   ├── useBoolean.tsx
│   │   │   ├── useClipboard.tsx
│   │   │   ├── useIsMobile.tsx
│   │   │   ├── useOverScroll.tsx
│   │   │   ├── useTocHighlight.tsx
│   │   │   └── utils/
│   │   │       └── throttle.ts
│   │   ├── index.d.ts
│   │   ├── lib/
│   │   │   ├── blog/
│   │   │   │   └── mdxUtils.ts
│   │   │   ├── docs/
│   │   │   │   ├── config.ts
│   │   │   │   ├── findRouteByPath.tsx
│   │   │   │   ├── md-loader.js
│   │   │   │   ├── page.tsx
│   │   │   │   ├── rehype-docs.js
│   │   │   │   ├── remark-paragraph-alerts.js
│   │   │   │   ├── remark-plugins.js
│   │   │   │   └── utils.ts
│   │   │   ├── fs-utils.tsx
│   │   │   ├── get-route-context.tsx
│   │   │   ├── github/
│   │   │   │   ├── api.tsx
│   │   │   │   ├── constants.tsx
│   │   │   │   └── raw.tsx
│   │   │   └── types.tsx
│   │   ├── manifests/
│   │   │   ├── getManifest.ts
│   │   │   ├── manifest-1.3.0.json
│   │   │   ├── manifest-2.1.4.json
│   │   │   └── manifest.json
│   │   ├── pages/
│   │   │   ├── _app.js
│   │   │   ├── _document.js
│   │   │   ├── blog/
│   │   │   │   ├── [slug].tsx
│   │   │   │   └── index.tsx
│   │   │   ├── docs/
│   │   │   │   └── [...slug].tsx
│   │   │   ├── index.tsx
│   │   │   └── users.tsx
│   │   ├── siteConfig.tsx
│   │   ├── styles/
│   │   │   └── index.css
│   │   └── users.ts
│   ├── tailwind.config.js
│   └── tsconfig.json
└── yarn.lock
Download .txt
SYMBOL INDEX (203 symbols across 69 files)

FILE: app/pages/_app.js
  function MyApp (line 4) | function MyApp({ Component, pageProps }) {

FILE: app/pages/index.tsx
  function Home (line 4) | function Home() {

FILE: examples/FastField.js
  class Input (line 5) | class Input extends React.Component {
    method render (line 7) | render() {

FILE: examples/RoutedMultistepWizard.js
  class WizardBase (line 16) | class WizardBase extends React.Component {
    method constructor (line 19) | constructor(props) {
    method render (line 63) | render() {

FILE: examples/basic-typescript/index.tsx
  type Values (line 6) | interface Values {

FILE: examples/dependent-fields-async-api-request/index.js
  function fetchNewTextC (line 6) | async function fetchNewTextC(a, b) {
  function App (line 41) | function App() {

FILE: examples/dependent-fields/index.js
  function App (line 34) | function App() {

FILE: packages/formik-native/src/index.ts
  function useSubmitButton (line 5) | function useSubmitButton() {

FILE: packages/formik/src/ErrorMessage.tsx
  type ErrorMessageProps (line 6) | interface ErrorMessageProps {
  class ErrorMessageImpl (line 15) | class ErrorMessageImpl extends React.Component<
    method shouldComponentUpdate (line 18) | shouldComponentUpdate(
    method render (line 34) | render() {

FILE: packages/formik/src/FastField.tsx
  type $FixMe (line 15) | type $FixMe = any;
  type FastFieldProps (line 17) | interface FastFieldProps<V = any> {
  type FastFieldConfig (line 23) | type FastFieldConfig<T> = FieldConfig & {
  type FastFieldAttributes (line 31) | type FastFieldAttributes<T> = GenericFieldHTMLAttributes &
  type FastFieldInnerProps (line 35) | type FastFieldInnerProps<Values = {}, Props = {}> = FastFieldAttributes<
  class FastFieldInner (line 43) | class FastFieldInner<Values = {}, Props = {}> extends React.Component<
    method constructor (line 47) | constructor(props: FastFieldInnerProps<Values, Props>) {
    method shouldComponentUpdate (line 75) | shouldComponentUpdate(props: FastFieldInnerProps<Values, Props>) {
    method componentDidMount (line 95) | componentDidMount() {
    method componentDidUpdate (line 103) | componentDidUpdate(prevProps: FastFieldAttributes<Props>) {
    method componentWillUnmount (line 118) | componentWillUnmount() {
    method render (line 122) | render() {

FILE: packages/formik/src/Field.tsx
  type FieldProps (line 14) | interface FieldProps<V = any, FormValues = any> {
  type FieldConfig (line 20) | interface FieldConfig<V = any> {
  type FieldAttributes (line 75) | type FieldAttributes<T> = { className?: string; } & GenericFieldHTMLAttr...
  type FieldHookConfig (line 81) | type FieldHookConfig<T> = GenericFieldHTMLAttributes & FieldConfig<T>;
  function useField (line 83) | function useField<Val = any>(
  function Field (line 137) | function Field({

FILE: packages/formik/src/FieldArray.tsx
  type FieldArrayRenderProps (line 20) | type FieldArrayRenderProps = ArrayHelpers & {
  type FieldArrayConfig (line 25) | type FieldArrayConfig = {
  type ArrayHelpers (line 31) | interface ArrayHelpers<T extends any[] = any[]> {
  class FieldArrayInner (line 140) | class FieldArrayInner<Values = {}> extends React.Component<
    method constructor (line 148) | constructor(props: FieldArrayConfig & { formik: FormikContextType<Valu...
    method componentDidUpdate (line 156) | componentDidUpdate(
    method remove (line 290) | remove<T>(index: number): T {
    method pop (line 319) | pop<T>(): T {
    method render (line 340) | render() {

FILE: packages/formik/src/Form.tsx
  type FormikFormProps (line 4) | type FormikFormProps = Pick<
  type FormProps (line 12) | type FormProps = React.ComponentPropsWithoutRef<'form'>;

FILE: packages/formik/src/Formik.tsx
  type FormikMessage (line 34) | type FormikMessage<Values> =
  function formikReducer (line 57) | function formikReducer<Values>(
  type FieldRegistry (line 128) | interface FieldRegistry {
  function useFormik (line 134) | function useFormik<Values extends FormikValues = FormikValues>({
  function Formik (line 1003) | function Formik<
  function warnAboutMissingIdentifier (line 1042) | function warnAboutMissingIdentifier({
  function yupToFormErrors (line 1062) | function yupToFormErrors<Values>(yupError: any): FormikErrors<Values> {
  function validateYupSchema (line 1080) | function validateYupSchema<T extends FormikValues>(
  function prepareDataForValidation (line 1097) | function prepareDataForValidation<T extends FormikValues>(
  function arrayMerge (line 1126) | function arrayMerge(target: any[], source: any[], options: any): any[] {
  function getSelectedValues (line 1146) | function getSelectedValues(options: any[]) {
  function getValueForCheckbox (line 1153) | function getValueForCheckbox(
  function useEventCallback (line 1207) | function useEventCallback<T extends (...args: any[]) => any>(fn: T): T {

FILE: packages/formik/src/FormikContext.tsx
  function useFormikContext (line 13) | function useFormikContext<Values>() {

FILE: packages/formik/src/connect.tsx
  function connect (line 12) | function connect<OuterProps, Values = {}>(

FILE: packages/formik/src/types.tsx
  type FormikValues (line 6) | interface FormikValues {
  type FormikErrors (line 14) | type FormikErrors<Values> = {
  type FormikTouched (line 27) | type FormikTouched<Values> = {
  type FormikState (line 40) | interface FormikState<Values> {
  type FormikComputedProps (line 60) | interface FormikComputedProps<Values> {
  type FormikHelpers (line 78) | interface FormikHelpers<Values> {
  type FormikHandlers (line 129) | interface FormikHandlers {
  type FormikSharedConfig (line 163) | interface FormikSharedConfig<Props = {}> {
  type FormikConfig (line 179) | interface FormikConfig<Values> extends FormikSharedConfig {
  type FormikProps (line 245) | type FormikProps<Values> = FormikSharedConfig &
  type FormikRegistration (line 253) | interface FormikRegistration {
  type FormikContextType (line 261) | type FormikContextType<Values> = FormikProps<Values> &
  type SharedRenderProps (line 264) | interface SharedRenderProps<T> {
  type GenericFieldHTMLAttributes (line 281) | type GenericFieldHTMLAttributes =
  type FieldMetaProps (line 287) | interface FieldMetaProps<Value> {
  type FieldHelperProps (line 303) | interface FieldHelperProps<Value> {
  type FieldInputProps (line 313) | interface FieldInputProps<Value> {
  type FieldValidator (line 328) | type FieldValidator = (

FILE: packages/formik/src/utils.ts
  function getActiveElement (line 54) | function getActiveElement(doc?: Document): Element | null {
  function getIn (line 69) | function getIn(
  function setIn (line 112) | function setIn(obj: any, path: string, value: any): any {
  function setNestedObjectValues (line 158) | function setNestedObjectValues<T>(

FILE: packages/formik/src/withFormik.tsx
  type InjectedFormikProps (line 20) | type InjectedFormikProps<Props, Values> = Props & FormikProps<Values>;
  type FormikBag (line 25) | type FormikBag<P, V> = { props: P } & FormikHelpers<V>;
  type WithFormikConfig (line 30) | interface WithFormikConfig<
  type CompositeComponent (line 82) | type CompositeComponent<P> =
  type ComponentDecorator (line 86) | interface ComponentDecorator<TOwnProps, TMergedProps> {
  type InferableComponentDecorator (line 90) | interface InferableComponentDecorator<TOwnProps> {
  function withFormik (line 97) | function withFormik<

FILE: packages/formik/test/ErrorMessage.test.tsx
  type TestFormValues (line 6) | interface TestFormValues {

FILE: packages/formik/test/Field.test.tsx
  type Values (line 23) | type Values = typeof initialValues;
  type FastFieldConfig (line 24) | type FastFieldConfig = FieldConfig;
  type $FixMe (line 26) | type $FixMe = any;
  function renderForm (line 28) | function renderForm(
  method getProps (line 73) | getProps() {
  function cases (line 86) | function cases(
  constant TEXT (line 96) | const TEXT = 'Mrs. Kato';

FILE: packages/formik/test/Formik.test.tsx
  type Values (line 22) | interface Values {
  function Form (line 27) | function Form({
  function renderFormik (line 78) | function renderFormik<V extends FormikValues = Values>(
  class SomeClass (line 1077) | class SomeClass {}
  class SomeClass (line 1090) | class SomeClass {}
  class SomeClass (line 1103) | class SomeClass {}

FILE: packages/formik/test/types.test.tsx
  type Values (line 5) | type Values = {

FILE: packages/formik/test/utils.test.tsx
  class TestClass (line 312) | class TestClass {
    method constructor (line 313) | constructor(public key: string, public setObj?: any) {}

FILE: packages/formik/test/withFormik.test.tsx
  type Values (line 8) | interface Values {
  method getProps (line 61) | getProps() {

FILE: packages/formik/types/index.d.ts
  type Options (line 27) | interface Options {
  type Task (line 50) | interface Task {
  type ScheduleCallbackOptions (line 54) | interface ScheduleCallbackOptions {

FILE: scripts/benchmark.tsx
  function FormikSimpleExample (line 34) | function FormikSimpleExample() {
  function ReactHookFormSimpleExample (line 73) | function ReactHookFormSimpleExample() {

FILE: website/next.config.js
  method rewrites (line 12) | rewrites() {

FILE: website/scripts/build-sitemap.js
  constant BUILD_ID (line 6) | const BUILD_ID = fs.readFileSync('.next/BUILD_ID').toString();

FILE: website/src/components/ArrowRight.tsx
  function ArrowRight (line 3) | function ArrowRight({ fill = '#718096', width = 6, height = 10 }: any) {

FILE: website/src/components/Banner.tsx
  function Banner (line 3) | function Banner() {

FILE: website/src/components/DocsPageFooter.tsx
  type DocsPageFooterProps (line 9) | interface DocsPageFooterProps {
  function areEqual (line 16) | function areEqual(prevProps: DocsPageFooterProps, props: DocsPageFooterP...

FILE: website/src/components/ExternalLink.tsx
  function ExternalLink (line 3) | function ExternalLink(props: any) {

FILE: website/src/components/Footer.tsx
  type FooterProps (line 6) | interface FooterProps {}

FILE: website/src/components/LayoutDocs.tsx
  type DocsProps (line 29) | interface DocsProps {
  function getCategoryPath (line 133) | function getCategoryPath(routes: RouteItem[]) {
  function SidebarRoutes (line 138) | function SidebarRoutes({

FILE: website/src/components/Logo.tsx
  function Logo (line 3) | function Logo() {

FILE: website/src/components/ReactionForm.tsx
  type FeedbackButtonProps (line 7) | interface FeedbackButtonProps {
  function FeedbackButton (line 19) | function FeedbackButton({ intent, ...props }: FeedbackButtonProps) {
  function ReactionForm (line 52) | function ReactionForm() {

FILE: website/src/components/Search.tsx
  type SearchProps (line 9) | interface SearchProps {
  function Hit (line 17) | function Hit({ hit, children }: any) {
  method navigate (line 147) | navigate({ suggestionUrl }: any) {

FILE: website/src/components/Seo.tsx
  type SeoProps (line 5) | interface SeoProps {

FILE: website/src/components/SidebarCategory.tsx
  function SidebarCategory (line 5) | function SidebarCategory({

FILE: website/src/components/SidebarMobile.tsx
  function SidebarMobile (line 14) | function SidebarMobile({ children }: { children: React.ReactNode }) {

FILE: website/src/components/SidebarNavLink.tsx
  type SidebarNavLinkProps (line 6) | interface SidebarNavLinkProps {
  function SidebarNavLink (line 14) | function SidebarNavLink({

FILE: website/src/components/Sticky.tsx
  type StickyProps (line 5) | interface StickyProps {

FILE: website/src/components/TWButton.tsx
  type TWButtonProps (line 5) | interface TWButtonProps {

FILE: website/src/components/Toc.tsx
  constant TOP_OFFSET (line 7) | const TOP_OFFSET = 100;
  function getHeaderAnchors (line 9) | function getHeaderAnchors(): Element[] {
  function getHeaderDataFromAnchors (line 20) | function getHeaderDataFromAnchors(el: Element) {

FILE: website/src/components/addRouterEvents.tsx
  function hasModifier (line 3) | function hasModifier(event: any) {
  function addRouterEvents (line 9) | function addRouterEvents(

FILE: website/src/components/clients/Client.tsx
  type ClientProps (line 4) | interface ClientProps {

FILE: website/src/components/forwardRefWithAs.tsx
  type AssignableRef (line 9) | type AssignableRef<ValueType> =
  type As (line 23) | type As<BaseProps = any> = React.ElementType<BaseProps>;
  type PropsWithAs (line 25) | type PropsWithAs<
  type PropsFromAs (line 36) | type PropsFromAs<
  type ComponentWithForwardedRef (line 42) | type ComponentWithForwardedRef<
  type ComponentWithAs (line 51) | interface ComponentWithAs<ComponentType extends As, ComponentProps> {
  function forwardRefWithAs (line 83) | function forwardRefWithAs<Props, ComponentType extends As>(

FILE: website/src/components/useBoolean.tsx
  type BooleanUpdater (line 3) | interface BooleanUpdater {

FILE: website/src/components/useClipboard.tsx
  function useClipboard (line 10) | function useClipboard(text: string, timeout = 1500) {

FILE: website/src/components/useTocHighlight.tsx
  type HeadingData (line 3) | interface HeadingData {
  function useTocHighlight (line 11) | function useTocHighlight(

FILE: website/src/lib/blog/mdxUtils.ts
  constant POSTS_PATH (line 5) | const POSTS_PATH = path.join(process.cwd(), 'src', 'blog');

FILE: website/src/lib/docs/config.ts
  constant TAG (line 2) | const TAG = 'v2.4.0';
  constant FORCE_TAG (line 5) | const FORCE_TAG = true;

FILE: website/src/lib/docs/findRouteByPath.tsx
  function findRouteByPath (line 5) | function findRouteByPath(path: string, routes: RouteItem[]): RouteItem {

FILE: website/src/lib/docs/page.tsx
  function getCurrentTag (line 12) | async function getCurrentTag(tag?: string) {
  function getRawFileFromLocal (line 20) | async function getRawFileFromLocal(path: string) {
  function fetchLocalDocsManifest (line 26) | async function fetchLocalDocsManifest() {
  function fetchRemoteDocsManifest (line 31) | async function fetchRemoteDocsManifest(tag: string) {
  function getPaths (line 36) | function getPaths(

FILE: website/src/lib/docs/rehype-docs.js
  constant ABSOLUTE_URL (line 7) | const ABSOLUTE_URL = /^https?:\/\/|^\/\//i;
  constant SITE_URL (line 8) | const SITE_URL = /^(https?:\/\/|^\/\/)formik\.org/i;
  constant HEADINGS (line 10) | const HEADINGS = ['h2', 'h3', 'h4', 'h5', 'h6'];
  function removeExt (line 12) | function removeExt(path) {
  function visitCard (line 20) | function visitCard(node) {
  function rehypeDocs (line 49) | function rehypeDocs({ filePath, tag }) {

FILE: website/src/lib/docs/utils.ts
  function getSlug (line 3) | function getSlug({ slug }: { slug: string[] }) {
  function removeFromLast (line 16) | function removeFromLast(path: string, key: string) {
  function addTagToSlug (line 21) | function addTagToSlug(slug: string, tag?: string) {

FILE: website/src/lib/get-route-context.tsx
  type RouteContext (line 3) | interface RouteContext {
  function getRouteContext (line 12) | function getRouteContext(

FILE: website/src/lib/github/api.tsx
  constant USE_CACHE (line 6) | const USE_CACHE = process.env.USE_CACHE === 'true';
  constant TAG_CACHE_PATH (line 7) | const TAG_CACHE_PATH = path.resolve('.github-latest-tag');
  function getLatestTag (line 9) | async function getLatestTag() {

FILE: website/src/lib/github/constants.tsx
  constant GITHUB_URL (line 1) | const GITHUB_URL = 'https://github.com';
  constant GITHUB_API_URL (line 3) | const GITHUB_API_URL = 'https://api.github.com';
  constant RAW_GITHUB_URL (line 5) | const RAW_GITHUB_URL = 'https://raw.githubusercontent.com';
  constant REPO_NAME (line 7) | const REPO_NAME = 'formik/formik';

FILE: website/src/lib/github/raw.tsx
  function getErrorText (line 4) | function getErrorText(res: Response) {
  type GHError (line 12) | type GHError = Error & { status?: Response['status']; headers?: any };
  function getError (line 14) | async function getError(res: Response): Promise<GHError> {
  function getRawFileFromGitHub (line 26) | async function getRawFileFromGitHub(path: string) {
  function getRawFileFromRepo (line 33) | async function getRawFileFromRepo(path: string, tag: string) {

FILE: website/src/lib/types.tsx
  type RouteItem (line 1) | interface RouteItem {
  type Routes (line 9) | interface Routes {
  type Page (line 13) | interface Page {
  type Post (line 21) | interface Post {

FILE: website/src/pages/_app.js
  function MyApp (line 5) | function MyApp({ Component, pageProps }) {

FILE: website/src/pages/_document.js
  class MyDocument (line 3) | class MyDocument extends Document {
    method render (line 4) | render() {

FILE: website/src/pages/blog/[slug].tsx
  function PostPage (line 19) | function PostPage({ source, frontMatter }: any) {

FILE: website/src/pages/blog/index.tsx
  function Index (line 17) | function Index({ posts }: any) {
  function getStaticProps (line 127) | function getStaticProps() {

FILE: website/src/pages/docs/[...slug].tsx
  type DocsProps (line 43) | interface DocsProps {
  function Docs (line 49) | function Docs({ page, routes, route: _route }: DocsProps) {
  function getCategoryPath (line 167) | function getCategoryPath(routes: RouteItem[]) {
  function SidebarRoutes (line 172) | function SidebarRoutes({

FILE: website/src/pages/index.tsx
  type HomeProps (line 17) | interface HomeProps {}

FILE: website/src/pages/users.tsx
  type UsersProps (line 14) | interface UsersProps {}
Condensed preview — 250 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,518K chars).
[
  {
    "path": ".all-contributorsrc",
    "chars": 3349,
    "preview": "{\n  \"projectName\": \"formik\",\n  \"projectOwner\": \"jaredpalmer\",\n  \"files\": [\n    \"packages/formik/README.md\"\n  ],\n  \"image"
  },
  {
    "path": ".changeset/README.md",
    "chars": 512,
    "preview": "# Changesets\n\nHello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that wo"
  },
  {
    "path": ".changeset/config.json",
    "chars": 291,
    "preview": "{\n  \"$schema\": \"https://unpkg.com/@changesets/config@1.3.0/schema.json\",\n  \"changelog\": [\"@changesets/changelog-github\","
  },
  {
    "path": ".codesandbox/ci.json",
    "chars": 146,
    "preview": "{\n  \"buildCommand\": \"build:codesandbox\",\n  \"node\": \"18\",\n  \"packages\": [\"packages/formik\", \"packages/formik-native\"],\n  "
  },
  {
    "path": ".eslintrc.js",
    "chars": 191,
    "preview": "module.exports = {\n  extends: [\n    'react-app',\n    'prettier/@typescript-eslint',\n    'plugin:prettier/recommended',\n "
  },
  {
    "path": ".github/CODEOWNERS",
    "chars": 198,
    "preview": "# Learn how to add code owners here:\n# https://help.github.com/en/articles/about-code-owners\n\n*          @jaredpalmer @q"
  },
  {
    "path": ".github/CODE_OF_CONDUCT.md",
    "chars": 3213,
    "preview": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, w"
  },
  {
    "path": ".github/CONTRIBUTING.md",
    "chars": 7851,
    "preview": "# Contributing to Formik\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T E"
  },
  {
    "path": ".github/FUNDING.yml",
    "chars": 683,
    "preview": "# These are supported funding model platforms\n\ngithub: [jaredpalmer] # Replace with up to 4 GitHub Sponsors-enabled user"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/1.Bug-report.md",
    "chars": 965,
    "preview": "---\nname: Bug report\nabout: Create a bug report for Formik / examples\ntitle: ''\nlabels: 'Type: Bug'\nassignees: ''\n---\n\n#"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/2.Feature-request.md",
    "chars": 1040,
    "preview": "---\nname: Feature request\nabout: Request a new feature for Formik\ntitle: ''\nlabels: 'Type: Feature Request'\nassignees: '"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "chars": 317,
    "preview": "blank_issues_enabled: false\ncontact_links:\n  - name: Ask a question\n    url: https://github.com/formium/formik/discussio"
  },
  {
    "path": ".github/workflows/ci.yml",
    "chars": 4458,
    "preview": "name: ci\n\non:\n  pull_request:\n  push:\n    branches: [main]\n\njobs:\n  detectChangedSourceFiles:\n    name: 'determine chang"
  },
  {
    "path": ".github/workflows/release.yml",
    "chars": 672,
    "preview": "name: Release\non:\n  push:\n    branches:\n      - main\n      - next\njobs:\n  release:\n    runs-on: ubuntu-latest\n    if: gi"
  },
  {
    "path": ".github/workflows/stale.yml",
    "chars": 934,
    "preview": "name: \"Close stale issues/prs\"\non:\n  schedule:\n    - cron: \"1 0 * * *\"\n\njobs:\n  stale:\n    runs-on: ubuntu-latest\n    st"
  },
  {
    "path": ".gitignore",
    "chars": 361,
    "preview": "dist\ncompiled\n*.log\ncoverage\n.DS_Store\nnext.d.ts\nlegacy.d.ts\n.idea\n*.orig\noutput.txt\n\nnode_modules\npackage-lock.json\nyar"
  },
  {
    "path": ".kodiak.toml",
    "chars": 379,
    "preview": "# .kodiak.toml\nversion = 1\n\n[merge]\nautomerge_label = \"automerge\"\nrequire_automerge_label = false\nmethod = \"squash\"\ndele"
  },
  {
    "path": ".nvmrc",
    "chars": 4,
    "preview": "v18\n"
  },
  {
    "path": ".prettierrc",
    "chars": 111,
    "preview": "{\n  \"tabWidth\": 2,\n  \"trailingComma\": \"es5\",\n  \"semi\": true,\n  \"singleQuote\": true,\n  \"arrowParens\": \"avoid\"\n}\n"
  },
  {
    "path": ".vscode/settings.json",
    "chars": 164,
    "preview": "{\n  \"typescript.tsdk\": \"node_modules/typescript/lib\",\n  \"editor.formatOnSave\": false,\n  \"editor.codeActionsOnSave\": {\n  "
  },
  {
    "path": "LICENSE",
    "chars": 10139,
    "preview": "                             Apache License\n                       Version 2.0, January 2004\n                    https:/"
  },
  {
    "path": "SECURITY.md",
    "chars": 352,
    "preview": "# Security Policy\n\n## Supported Versions\n\n| Version | Supported          |\n| ------- | ------------------ |\n| 2.x.x     "
  },
  {
    "path": "app/.gitignore",
    "chars": 386,
    "preview": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pn"
  },
  {
    "path": "app/README.md",
    "chars": 191,
    "preview": "# Formik Integration Test App\n\nThis is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](ht"
  },
  {
    "path": "app/next-env.d.ts",
    "chars": 201,
    "preview": "/// <reference types=\"next\" />\n/// <reference types=\"next/image-types/global\" />\n\n// NOTE: This file should not be edite"
  },
  {
    "path": "app/package.json",
    "chars": 357,
    "preview": "{\n  \"name\": \"app\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"scripts\": {\n    \"dev\": \"next dev\",\n    \"build\": \"next bui"
  },
  {
    "path": "app/pages/_app.js",
    "chars": 167,
    "preview": "import React from 'react';\nimport '../styles/globals.css';\n\nfunction MyApp({ Component, pageProps }) {\n  return <Compone"
  },
  {
    "path": "app/pages/basic.js",
    "chars": 2647,
    "preview": "import React from 'react';\nimport { Formik, Field, Form, ErrorMessage } from 'formik';\nimport * as Yup from 'yup';\n\ncons"
  },
  {
    "path": "app/pages/index.tsx",
    "chars": 850,
    "preview": "import React from 'react';\nimport Link from 'next/link';\n\nfunction Home() {\n  return (\n    <main>\n      <h1>Formik Examp"
  },
  {
    "path": "app/pages/sign-in.js",
    "chars": 2423,
    "preview": "import React, { useEffect, useState } from 'react';\nimport { ErrorMessage, Field, Form, FormikProvider, useFormik } from"
  },
  {
    "path": "app/styles/globals.css",
    "chars": 275,
    "preview": "html,\nbody {\n  padding: 0;\n  margin: 0;\n  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,\n    "
  },
  {
    "path": "app/tsconfig.json",
    "chars": 522,
    "preview": "{\n  \"extends\": \"../tsconfig.base.json\",\n  \"compilerOptions\": {\n    \"target\": \"es5\",\n    \"lib\": [\n      \"dom\",\n      \"dom"
  },
  {
    "path": "docs/3rd-party-bindings.md",
    "chars": 808,
    "preview": "---\ntitle: 3rd Party Bindings\noriginal_id: 3rd-party-bindings\ndescription: Use Formik with popular React component libra"
  },
  {
    "path": "docs/api/connect.md",
    "chars": 912,
    "preview": "---\nid: connect\ntitle: connect()\n---\n\n`connect()` is a higher-order component (HoC) that allows you to hook anything int"
  },
  {
    "path": "docs/api/errormessage.md",
    "chars": 3696,
    "preview": "---\nid: errormessage\ntitle: <ErrorMessage />\n---\n\n`<ErrorMessage />` is a component that renders the error message of a "
  },
  {
    "path": "docs/api/fastfield.md",
    "chars": 5551,
    "preview": "---\nid: fastfield\ntitle: <FastField />\n---\n\n## Before we start\n\n`<FastField />` is meant for performance _optimization_."
  },
  {
    "path": "docs/api/field.md",
    "chars": 9339,
    "preview": "---\nid: field\ntitle: <Field />\n---\n\n`<Field />` will automagically hook up inputs to Formik. It uses the `name`\nattribut"
  },
  {
    "path": "docs/api/fieldarray.md",
    "chars": 8809,
    "preview": "---\nid: fieldarray\ntitle: <FieldArray />\n---\n\n`<FieldArray />` is a component that helps with common array/list manipula"
  },
  {
    "path": "docs/api/form.md",
    "chars": 372,
    "preview": "---\nid: form\ntitle: <Form />\n---\n\nForm is a small wrapper around an HTML `<form>` element that automatically hooks into "
  },
  {
    "path": "docs/api/formik.md",
    "chars": 17075,
    "preview": "---\nid: formik\ntitle: <Formik />\n---\n\n`<Formik>` is a component that helps you with building forms. It uses a render\npro"
  },
  {
    "path": "docs/api/useField.md",
    "chars": 7184,
    "preview": "---\nid: useField\ntitle: useField()\n---\n\n`useField` is a React hook used to thread Formik behaviors into arbitrary field "
  },
  {
    "path": "docs/api/useFormik.md",
    "chars": 2300,
    "preview": "---\nid: useFormik\ntitle: useFormik()\n---\n\n`useFormik()` is a custom React hook that will return all Formik state and hel"
  },
  {
    "path": "docs/api/useFormikContext.md",
    "chars": 1981,
    "preview": "---\nid: useFormikContext\ntitle: useFormikContext()\n---\n\n`useFormikContext()` is a custom React hook that will return all"
  },
  {
    "path": "docs/api/utils.md",
    "chars": 807,
    "preview": "---\nid: utils\ntitle: Utils\n---\n\n# Reference\n\n## Exported Functions\n\n#### `getActiveElement(doc?: Document): Element | nu"
  },
  {
    "path": "docs/api/withFormik.md",
    "chars": 7410,
    "preview": "---\nid: withFormik\ntitle: withFormik()\n---\n\nCreate a higher-order React component class that passes props and form handl"
  },
  {
    "path": "docs/examples/async-submission.md",
    "chars": 815,
    "preview": "---\ntitle: Async Submission Example\ndescription: This example demonstrates how to use async/await to submit a Formik for"
  },
  {
    "path": "docs/examples/basic.md",
    "chars": 775,
    "preview": "---\ntitle: Basic Example\ndescription: This example demonstrates how to use Formik in its most basic way.\n---\n\nThis examp"
  },
  {
    "path": "docs/examples/checkboxes.md",
    "chars": 993,
    "preview": "---\ntitle: Checkboxes Example\ndescription: This example demonstrates how to use Formik with a checkbox group. Given that"
  },
  {
    "path": "docs/examples/dependent-fields-async-api-request.md",
    "chars": 1078,
    "preview": "---\ntitle: Dependent fields with an Async API Request Example\ndescription: This is an example of a complex dependent fie"
  },
  {
    "path": "docs/examples/dependent-fields.md",
    "chars": 885,
    "preview": "---\ntitle: Dependent Fields Example\ndescription: This is an example of how to set the value of one field based on the cu"
  },
  {
    "path": "docs/examples/field-arrays.md",
    "chars": 709,
    "preview": "---\ntitle: Field Arrays Example\n---\n\nThis example demonstrates how to work with array fields in Formik.\n\n<div className="
  },
  {
    "path": "docs/examples/instant-feedback.md",
    "chars": 1079,
    "preview": "---\ntitle: Accessible Instant Feedback Example\n---\n\nInstant feedback during typing can be extremely helpful in certain s"
  },
  {
    "path": "docs/examples/more-examples.md",
    "chars": 173,
    "preview": "---\ntitle: More Examples\n---\n\nYou can find additional examples in [`examples` folder of the Formik GitHub repository](ht"
  },
  {
    "path": "docs/examples/radio-group.md",
    "chars": 787,
    "preview": "---\ntitle: Radio Group Example\ndescription: This example demonstrates how to create a radio group with Formik.\n---\n\nThis"
  },
  {
    "path": "docs/examples/typescript.md",
    "chars": 821,
    "preview": "---\ntitle: Basic TypeScript\ndescription: This example demonstrates how to use Formik in its most basic way with TypeScri"
  },
  {
    "path": "docs/examples/with-material-ui.md",
    "chars": 868,
    "preview": "---\nid: with-material-ui\ntitle: Material UI\n---\n\nFormik can be easily used/integrated with [Material UI](https://materia"
  },
  {
    "path": "docs/examples.md",
    "chars": 542,
    "preview": "---\nid: examples\ntitle: Examples\ndescription: Runnable examples of using Formik in React and React Native to create form"
  },
  {
    "path": "docs/guides/arrays.md",
    "chars": 2407,
    "preview": "---\nid: arrays\ntitle: Arrays and Nested Objects\n---\n\nFormik has support for nested objects and arrays out of the box. Th"
  },
  {
    "path": "docs/guides/form-submission.md",
    "chars": 2303,
    "preview": "---\nid: form-submission\ntitle: Form Submission\n---\n\n## Submission Phases\n\nTo submit a form in Formik, you need to someho"
  },
  {
    "path": "docs/guides/react-native.md",
    "chars": 1795,
    "preview": "---\nid: react-native\ntitle: React Native\n---\n\n**Formik is 100% compatible with React Native and React Native Web.** Howe"
  },
  {
    "path": "docs/guides/typescript.md",
    "chars": 3252,
    "preview": "---\nid: typescript\ntitle: TypeScript\n---\n\nThe Formik source code is written in TypeScript, so you can rest easy that For"
  },
  {
    "path": "docs/guides/validation.md",
    "chars": 11065,
    "preview": "---\nid: validation\ntitle: Validation\n---\n\nFormik is designed to manage forms with complex validation with ease. Formik s"
  },
  {
    "path": "docs/manifest.json",
    "chars": 4013,
    "preview": "{\n  \"routes\": [\n    {\n      \"title\": \"Documentation\",\n      \"heading\": true,\n      \"routes\": [\n        {\n          \"titl"
  },
  {
    "path": "docs/migrating-v2.md",
    "chars": 10736,
    "preview": "---\nid: migrating-v2\ntitle: Migrating from v1.x to v2.x\ndescription: How to migrate from Formik v1 to v2\n---\n\n## Breakin"
  },
  {
    "path": "docs/overview.md",
    "chars": 8292,
    "preview": "---\nid: overview\ntitle: Overview\ndescription: Formik documentation, tutorial, guides, and examples\n---\n\nLet's face it, f"
  },
  {
    "path": "docs/resources.md",
    "chars": 3937,
    "preview": "---\nid: resources\ntitle: Resources\ndescription: Formik conference talks, courses, videos, blog posts, learning resources"
  },
  {
    "path": "docs/tutorial.md",
    "chars": 37157,
    "preview": "---\nid: tutorial\ntitle: Tutorial\ndescription: Learn how to build forms in React with Formik.\n---\n\n## Before we start\n\nWe"
  },
  {
    "path": "e2e/basic.test.ts",
    "chars": 2739,
    "preview": "import { test, expect } from '@playwright/test';\n\ntest('should validate before submit', async ({ page }) => {\n  await pa"
  },
  {
    "path": "examples/AsyncValidation.js",
    "chars": 1170,
    "preview": "import React from 'react';\nimport { Formik, Field, Form, ErrorMessage } from 'formik';\nimport { Debug } from './Debug';\n"
  },
  {
    "path": "examples/CombinedValidations.js",
    "chars": 2096,
    "preview": "import React from 'react';\nimport { Formik, Field, Form, ErrorMessage } from 'formik';\nimport * as Yup from 'yup';\nimpor"
  },
  {
    "path": "examples/CustomInputs.js",
    "chars": 2413,
    "preview": "import React from 'react';\nimport { Formik, Field, Form, ErrorMessage } from 'formik';\nimport * as Yup from 'yup';\nimpor"
  },
  {
    "path": "examples/DebouncedAutoSave.js",
    "chars": 1919,
    "preview": "import React from 'react';\nimport { useFormikContext, Formik, Field, Form } from 'formik';\nimport { Debug } from './Debu"
  },
  {
    "path": "examples/Debug.js",
    "chars": 914,
    "preview": "import React from 'react';\nimport { FormikConsumer } from 'formik';\n\nexport const Debug = () => (\n  <div\n    style={{\n  "
  },
  {
    "path": "examples/ErrorMessage.js",
    "chars": 2321,
    "preview": "import React from 'react';\nimport { Formik, Field, Form, ErrorMessage } from 'formik';\nimport * as Yup from 'yup';\nimpor"
  },
  {
    "path": "examples/FastField.js",
    "chars": 1488,
    "preview": "import React from 'react';\nimport { Formik, FastField, Form } from 'formik';\nimport { Debug } from './Debug';\n\nclass Inp"
  },
  {
    "path": "examples/MultistepWizard.js",
    "chars": 4254,
    "preview": "import React, { useState } from 'react';\nimport { ErrorMessage, Field, Form, Formik } from 'formik';\nimport * as Yup fro"
  },
  {
    "path": "examples/RoutedMultistepWizard.js",
    "chars": 6214,
    "preview": "import React from 'react';\nimport { BrowserRouter as Router, Route, withRouter } from 'react-router-dom';\nimport { Formi"
  },
  {
    "path": "examples/RoutedMultistepWizard2.js",
    "chars": 2954,
    "preview": "/* eslint-disable jsx-a11y/accessible-emoji */\nimport React, { Fragment } from 'react';\nimport {\n  BrowserRouter as Rout"
  },
  {
    "path": "examples/SchemaValidation.js",
    "chars": 2139,
    "preview": "import React from 'react';\nimport { Formik, Field, Form, ErrorMessage } from 'formik';\nimport * as Yup from 'yup';\nimpor"
  },
  {
    "path": "examples/SyncValidation.js",
    "chars": 1186,
    "preview": "import React from 'react';\nimport { Formik, Field, Form, ErrorMessage } from 'formik';\nimport { Debug } from './Debug';\n"
  },
  {
    "path": "examples/ValidateFieldWithSchema.js",
    "chars": 2264,
    "preview": "import React from 'react';\nimport { Formik, Field, Form, ErrorMessage } from 'formik';\nimport { object, string } from 'y"
  },
  {
    "path": "examples/async-submission/README.md",
    "chars": 330,
    "preview": "# Formik Async Submission\n\nThis example demonstrates how to use async/await to submit a Formik form.\n\n[![Edit formik-exa"
  },
  {
    "path": "examples/async-submission/index.js",
    "chars": 1057,
    "preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport { Formik, Field, Form } from 'formik';\n\nconst sleep "
  },
  {
    "path": "examples/async-submission/package.json",
    "chars": 408,
    "preview": "{\n  \"name\": \"formik-example-async-submission\",\n  \"version\": \"0.1.0\",\n  \"description\": \"This example demonstrates how to "
  },
  {
    "path": "examples/basic/README.md",
    "chars": 298,
    "preview": "# Formik Basic Example\n\nThis example demonstrates how to use Formik in its most basic way.\n\n[![Edit formik-example-basic"
  },
  {
    "path": "examples/basic/index.js",
    "chars": 1000,
    "preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport { Formik, Field, Form } from 'formik';\n\nconst Basic "
  },
  {
    "path": "examples/basic/package.json",
    "chars": 391,
    "preview": "{\n  \"name\": \"formik-example-basic\",\n  \"version\": \"0.1.0\",\n  \"description\": \"This example demonstrates how to use Formik "
  },
  {
    "path": "examples/basic-typescript/README.md",
    "chars": 360,
    "preview": "# Formik TypeScript Example\n\nThis example demonstrates how to get started with Formik and [TypeScript](https://typescrip"
  },
  {
    "path": "examples/basic-typescript/index.html",
    "chars": 342,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-w"
  },
  {
    "path": "examples/basic-typescript/index.tsx",
    "chars": 1311,
    "preview": "import 'react-app-polyfill/ie11';\nimport * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport { Formik"
  },
  {
    "path": "examples/basic-typescript/package.json",
    "chars": 517,
    "preview": "{\n  \"name\": \"formik-basic-typescript-example\",\n  \"version\": \"0.1.0\",\n  \"description\": \"This example demonstrates how to "
  },
  {
    "path": "examples/basic-typescript/tsconfig.json",
    "chars": 458,
    "preview": "{\n  \"compilerOptions\": {\n    \"allowSyntheticDefaultImports\": false,\n    \"target\": \"es5\",\n    \"module\": \"commonjs\",\n    \""
  },
  {
    "path": "examples/checkboxes/README.md",
    "chars": 305,
    "preview": "# Formik Checkboxes\n\nThis example demonstrates how to use Formik with a checkbox group.\n\n[![Edit formik-example-checkbox"
  },
  {
    "path": "examples/checkboxes/index.js",
    "chars": 1784,
    "preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport { Formik, Field, Form } from 'formik';\n\nconst sleep "
  },
  {
    "path": "examples/checkboxes/package.json",
    "chars": 395,
    "preview": "{\n  \"name\": \"formik-example-checkboxes\",\n  \"version\": \"0.1.0\",\n  \"description\": \"This example demonstrates how to use Fo"
  },
  {
    "path": "examples/dependent-fields/README.md",
    "chars": 378,
    "preview": "# Formik Dependent Fields Example\n\nThis is an example of how to set the value of one field based on the current values o"
  },
  {
    "path": "examples/dependent-fields/index.js",
    "chars": 3301,
    "preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport { Formik, Field, Form, useField, useFormikContext } "
  },
  {
    "path": "examples/dependent-fields/package.json",
    "chars": 448,
    "preview": "{\n  \"name\": \"formik-example-dependent-fields\",\n  \"version\": \"0.1.0\",\n  \"description\": \"This is an example of how to set "
  },
  {
    "path": "examples/dependent-fields/styles.css",
    "chars": 234,
    "preview": ".App {\n  font-family: sans-serif;\n  max-width: 500px;\n}\n\n.section {\n  padding: 10px;\n  border: 1px solid purple;\n  borde"
  },
  {
    "path": "examples/dependent-fields-async-api-request/README.md",
    "chars": 502,
    "preview": "# Dependent Formik fields with Async API Request\n\nThis is an example of a complex dependent field in Formik v2. In this "
  },
  {
    "path": "examples/dependent-fields-async-api-request/index.js",
    "chars": 2514,
    "preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport { Formik, Field, Form, useField, useFormikContext } "
  },
  {
    "path": "examples/dependent-fields-async-api-request/package.json",
    "chars": 497,
    "preview": "{\n  \"name\": \"formik-example-dependent-fields-async-api-request\",\n  \"version\": \"0.1.0\",\n  \"description\": \"This is an exam"
  },
  {
    "path": "examples/dependent-fields-async-api-request/styles.css",
    "chars": 234,
    "preview": ".App {\n  font-family: sans-serif;\n  max-width: 500px;\n}\n\n.section {\n  padding: 10px;\n  border: 1px solid purple;\n  borde"
  },
  {
    "path": "examples/field-arrays/README.md",
    "chars": 313,
    "preview": "# Formik Arrays Example\n\nThis example demonstrates how to work with array fields in Formik.\n\n[![Edit formik-example-fiel"
  },
  {
    "path": "examples/field-arrays/index.js",
    "chars": 2785,
    "preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport { Formik, Field, Form, ErrorMessage, FieldArray } fr"
  },
  {
    "path": "examples/field-arrays/package.json",
    "chars": 397,
    "preview": "{\n  \"name\": \"formik-example-field-arrays\",\n  \"version\": \"0.1.0\",\n  \"description\": \"This example demonstrates how to work"
  },
  {
    "path": "examples/field-level-validation/README.md",
    "chars": 365,
    "preview": "# Formik Field-Level Validation Example via `<Field />`\n\nThis example demonstrates how to use field-level validation wit"
  },
  {
    "path": "examples/field-level-validation/index.js",
    "chars": 2269,
    "preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport { Formik, Field, Form, ErrorMessage, useFormikContex"
  },
  {
    "path": "examples/field-level-validation/package.json",
    "chars": 396,
    "preview": "{\n  \"name\": \"formik-example-radio-group\",\n  \"version\": \"0.1.0\",\n  \"description\": \"This example demonstrates how to creat"
  },
  {
    "path": "examples/instant-feedback/README.md",
    "chars": 693,
    "preview": "# Formik Accessible Instant Feedback Example\n\nInstant feedback during typing can be extremely helpful in certain situati"
  },
  {
    "path": "examples/instant-feedback/index.js",
    "chars": 4182,
    "preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport { useFormik, FormikProvider, Form, useField } from '"
  },
  {
    "path": "examples/instant-feedback/package.json",
    "chars": 382,
    "preview": "{\n  \"name\": \"accesible-instant-feedback-with-formik\",\n  \"version\": \"0.1.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n "
  },
  {
    "path": "examples/instant-feedback/styles.css",
    "chars": 14845,
    "preview": "* {\n  box-sizing: border-box;\n  margin: 0;\n  padding: 0;\n  text-rendering: optimizeLegibility;\n  -webkit-font-smoothing:"
  },
  {
    "path": "examples/radio-group/README.md",
    "chars": 316,
    "preview": "# Formik Radio Group Example\n\nThis example demonstrates how to create a radio group with Formik.\n\n[![Edit formik-example"
  },
  {
    "path": "examples/radio-group/index.js",
    "chars": 1000,
    "preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport { Formik, Field, Form } from 'formik';\n\nconst Exampl"
  },
  {
    "path": "examples/radio-group/package.json",
    "chars": 396,
    "preview": "{\n  \"name\": \"formik-example-radio-group\",\n  \"version\": \"0.1.0\",\n  \"description\": \"This example demonstrates how to creat"
  },
  {
    "path": "examples/with-material-ui/README.md",
    "chars": 124,
    "preview": "# Formik with Material UI\n\nThis example demonstrates how to use Formik with Material UI\n\n<!-- TODO add codesandbox link "
  },
  {
    "path": "examples/with-material-ui/index.js",
    "chars": 1891,
    "preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport { useFormik } from 'formik';\nimport * as yup from 'y"
  },
  {
    "path": "examples/with-material-ui/package.json",
    "chars": 448,
    "preview": "{\n  \"name\": \"formik-example-with-material-ui\",\n  \"version\": \"0.1.0\",\n  \"description\": \"This example demonstrates how to "
  },
  {
    "path": "examples/withFormik.js",
    "chars": 1331,
    "preview": "import React from 'react';\nimport * as Yup from 'yup';\nimport { withFormik, ErrorMessage } from '../src/formik';\nimport "
  },
  {
    "path": "package.json",
    "chars": 1808,
    "preview": "{\n  \"name\": \"formik-project\",\n  \"private\": true,\n  \"type\": \"module\",\n  \"packageManager\": \"yarn@1.22.22\",\n  \"resolutions\""
  },
  {
    "path": "packages/formik/.gitignore",
    "chars": 314,
    "preview": "node_modules\ndist\ncompiled\n*.log\ncoverage\n.DS_Store\nnext.d.ts\nlegacy.d.ts\n.idea\n*.orig\n.DS_Store\n\nnode_modules\n\nlib/core"
  },
  {
    "path": "packages/formik/CHANGELOG.md",
    "chars": 14730,
    "preview": "# formik\n\n## 2.4.9\n\n### Patch Changes\n\n- [#4051](https://github.com/jaredpalmer/formik/pull/4051) [`8f9d04d`](https://gi"
  },
  {
    "path": "packages/formik/MIGRATING-v2.md",
    "chars": 9279,
    "preview": "## Breaking Changes\n\n### Minimum Requirements\n\n- Since Formik 2 is built on top of React Hooks, you must be on React 16."
  },
  {
    "path": "packages/formik/README.md",
    "chars": 6268,
    "preview": "<p align=\"center\">\n  <img src=\"https://user-images.githubusercontent.com/4060187/61057426-4e5a4600-a3c3-11e9-9114-630743"
  },
  {
    "path": "packages/formik/package.json",
    "chars": 2051,
    "preview": "{\n  \"name\": \"formik\",\n  \"description\": \"Build forms in React, without the tears\",\n  \"version\": \"2.4.9\",\n  \"license\": \"Ap"
  },
  {
    "path": "packages/formik/src/ErrorMessage.tsx",
    "chars": 1641,
    "preview": "import * as React from 'react';\nimport { FormikContextType } from './types';\nimport { getIn, isFunction } from './utils'"
  },
  {
    "path": "packages/formik/src/FastField.tsx",
    "chars": 6056,
    "preview": "import * as React from 'react';\n\nimport {\n  FormikProps,\n  GenericFieldHTMLAttributes,\n  FormikContextType,\n  FieldMetaP"
  },
  {
    "path": "packages/formik/src/Field.tsx",
    "chars": 6326,
    "preview": "import * as React from 'react';\nimport {\n  FormikProps,\n  GenericFieldHTMLAttributes,\n  FieldMetaProps,\n  FieldHelperPro"
  },
  {
    "path": "packages/formik/src/FieldArray.tsx",
    "chars": 11012,
    "preview": "import cloneDeep from 'lodash/cloneDeep';\nimport * as React from 'react';\nimport isEqual from 'react-fast-compare';\nimpo"
  },
  {
    "path": "packages/formik/src/Form.tsx",
    "chars": 972,
    "preview": "import * as React from 'react';\nimport { useFormikContext } from './FormikContext';\n\nexport type FormikFormProps = Pick<"
  },
  {
    "path": "packages/formik/src/Formik.tsx",
    "chars": 38207,
    "preview": "import deepmerge from 'deepmerge';\nimport isPlainObject from 'lodash/isPlainObject';\nimport cloneDeep from 'lodash/clone"
  },
  {
    "path": "packages/formik/src/FormikContext.tsx",
    "chars": 660,
    "preview": "import * as React from 'react';\nimport { FormikContextType } from './types';\nimport invariant from 'tiny-warning';\n\nexpo"
  },
  {
    "path": "packages/formik/src/connect.tsx",
    "chars": 1567,
    "preview": "import * as React from 'react';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\n\nimport { FormikContextType "
  },
  {
    "path": "packages/formik/src/index.tsx",
    "chars": 306,
    "preview": "export * from './Formik';\nexport * from './Field';\nexport * from './Form';\nexport * from './withFormik';\nexport * from '"
  },
  {
    "path": "packages/formik/src/types.tsx",
    "chars": 10337,
    "preview": "import * as React from 'react';\nimport { FieldConfig } from './Field';\n/**\n * Values of fields in the form\n */\nexport in"
  },
  {
    "path": "packages/formik/src/utils.ts",
    "chars": 5775,
    "preview": "import clone from 'lodash/clone';\nimport toPath from 'lodash/toPath';\nimport * as React from 'react';\n\n// Assertions\n\n/*"
  },
  {
    "path": "packages/formik/src/withFormik.tsx",
    "chars": 5426,
    "preview": "import hoistNonReactStatics from 'hoist-non-react-statics';\nimport * as React from 'react';\nimport { Formik } from './Fo"
  },
  {
    "path": "packages/formik/test/ErrorMessage.test.tsx",
    "chars": 1376,
    "preview": "import * as React from 'react';\nimport { act, render } from '@testing-library/react';\nimport { Formik, FormikProps, Erro"
  },
  {
    "path": "packages/formik/test/Field.test.tsx",
    "chars": 18440,
    "preview": "import * as React from 'react';\nimport {\n  act,\n  cleanup,\n  render,\n  waitFor,\n  fireEvent,\n} from '@testing-library/re"
  },
  {
    "path": "packages/formik/test/FieldArray.test.tsx",
    "chars": 19922,
    "preview": "import { act, fireEvent, render, screen } from '@testing-library/react';\nimport * as React from 'react';\nimport * as Yup"
  },
  {
    "path": "packages/formik/test/Formik.test.tsx",
    "chars": 44454,
    "preview": "import * as React from 'react';\nimport {\n  act,\n  fireEvent,\n  render,\n  screen,\n  waitFor,\n} from '@testing-library/rea"
  },
  {
    "path": "packages/formik/test/setupTests.ts",
    "chars": 689,
    "preview": "const consoleError = console.error;\n\nlet consoleErrorLog: any[] = [];\n\nbeforeEach(() => {\n  consoleErrorLog = [];\n  // M"
  },
  {
    "path": "packages/formik/test/testHelpers.ts",
    "chars": 156,
    "preview": "// tslint:disable-next-line:no-empty\nexport const noop = () => {};\n\nexport const sleep = (ms: number) =>\n  new Promise(r"
  },
  {
    "path": "packages/formik/test/tsconfig.json",
    "chars": 144,
    "preview": "{\n  // Hack to fix https://github.com/formium/tsdx/issues/84#issuecomment-489690504\n  \"extends\": \"../../../tsconfig.json"
  },
  {
    "path": "packages/formik/test/types.test.tsx",
    "chars": 1348,
    "preview": "import { FormikTouched, FormikErrors } from '../src';\n\ndescribe('Formik Types', () => {\n  describe('FormikTouched', () ="
  },
  {
    "path": "packages/formik/test/utils.test.tsx",
    "chars": 11505,
    "preview": "import {\n  isEmptyArray,\n  setIn,\n  getIn,\n  setNestedObjectValues,\n  isPromise,\n  getActiveElement,\n  isNaN,\n} from '.."
  },
  {
    "path": "packages/formik/test/withFormik.test.tsx",
    "chars": 5777,
    "preview": "import * as React from 'react';\nimport { act, render, waitFor } from '@testing-library/react';\nimport * as Yup from 'yup"
  },
  {
    "path": "packages/formik/test/yupHelpers.test.ts",
    "chars": 3126,
    "preview": "import * as Yup from 'yup';\nimport { validateYupSchema, yupToFormErrors } from '../src';\n\nconst schema = Yup.object().sh"
  },
  {
    "path": "packages/formik/tsconfig.build.json",
    "chars": 126,
    "preview": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [\"src\", \"types\"],\n  \"compilerOptions\": {\n    \"rootDir\": \"./src\"\n"
  },
  {
    "path": "packages/formik/types/global.d.ts",
    "chars": 260,
    "preview": "// Declare global variables for TypeScript and VSCode.\n// Do not rename this file or move these types into index.d.ts\n//"
  },
  {
    "path": "packages/formik/types/index.d.ts",
    "chars": 1548,
    "preview": "declare module 'tiny-warning' {\n  export default function warning(condition: any, message: string): void;\n}\n\ndeclare mod"
  },
  {
    "path": "packages/formik-native/.gitignore",
    "chars": 82,
    "preview": "*.log\n.DS_Store\nnode_modules\n.rts2_cache_cjs\n.rts2_cache_esm\n.rts2_cache_umd\ndist\n"
  },
  {
    "path": "packages/formik-native/CHANGELOG.md",
    "chars": 6643,
    "preview": "# formik-native\n\n## 2.1.32\n\n### Patch Changes\n\n- Updated dependencies [[`8f9d04d`](https://github.com/jaredpalmer/formik"
  },
  {
    "path": "packages/formik-native/CONTRIBUTING.md",
    "chars": 1080,
    "preview": "# TSDX Bootstrap\n\nThis project was bootstrapped with [TSDX](https://github.com/jaredpalmer/tsdx).\n\n## Local Development\n"
  },
  {
    "path": "packages/formik-native/README.md",
    "chars": 115,
    "preview": "# Formik Native\n\n```\nyarn add formik formik-native\n```\n\nThis is an experimental package. DO NOT USE IN PRODUCTION.\n"
  },
  {
    "path": "packages/formik-native/package.json",
    "chars": 1098,
    "preview": "{\n  \"name\": \"formik-native\",\n  \"version\": \"2.1.32\",\n  \"license\": \"Apache-2.0\",\n  \"author\": \"Jared Palmer <jared@palmer.n"
  },
  {
    "path": "packages/formik-native/src/index.ts",
    "chars": 410,
    "preview": "import * as React from 'react';\nimport { NativeSyntheticEvent, NativeTouchEvent } from 'react-native';\nimport { useFormi"
  },
  {
    "path": "packages/formik-native/test/blah.test.ts",
    "chars": 83,
    "preview": "describe('blah', () => {\n  it('works', () => {\n    expect(1).toEqual(1);\n  });\n});\n"
  },
  {
    "path": "packages/formik-native/tsconfig.build.json",
    "chars": 216,
    "preview": "{\n  \"extends\": \"../../tsconfig.json\",\n  \"include\": [\"src\", \"types\"],\n  \"compilerOptions\": {\n    \"target\": \"es5\",\n    \"mo"
  },
  {
    "path": "playwright.config.ts",
    "chars": 2251,
    "preview": "import { PlaywrightTestProject, defineConfig, devices } from '@playwright/test';\n\n/**\n * Read environment variables from"
  },
  {
    "path": "scripts/benchmark.tsx",
    "chars": 3222,
    "preview": "import { yupResolver } from '@hookform/resolvers/yup';\nimport Benchmark from 'benchmark';\nimport { Field, FieldArray, Fo"
  },
  {
    "path": "scripts/btag.sh",
    "chars": 59,
    "preview": "#!/bin/bash\n\ngit branch $1-branch $1\ngit checkout $1-branch"
  },
  {
    "path": "scripts/retag.sh",
    "chars": 93,
    "preview": "#!/bin/bash\n\ngit tag -d $1\ngit tag $1\ngit push origin :$1\ngit push origin $1\ngit fetch --tags"
  },
  {
    "path": "tsconfig.base.json",
    "chars": 1339,
    "preview": "{\n  \"compilerOptions\": {\n    \"module\": \"esnext\",\n    \"lib\": [\"dom\", \"esnext\"],\n    \"importHelpers\": true,\n    \"noImplici"
  },
  {
    "path": "tsconfig.json",
    "chars": 359,
    "preview": "{\n  \"extends\": \"./tsconfig.base.json\",\n  \"include\": [\"packages\", \"types\", \"scripts\"],\n  \"compilerOptions\": {\n    \"allowJ"
  },
  {
    "path": "turbo.json",
    "chars": 372,
    "preview": "{\n  \"$schema\": \"https://turborepo.com/schema.json\",\n  \"tasks\": {\n    \"build\": {\n      \"dependsOn\": [\"^build\"],\n      \"ou"
  },
  {
    "path": "website/.eslintignore",
    "chars": 38,
    "preview": "**/node_modules/*\n**/out/*\n**/.next/*\n"
  },
  {
    "path": "website/.eslintrc",
    "chars": 39,
    "preview": "{\n  \"extends\": \"next/core-web-vitals\"\n}"
  },
  {
    "path": "website/.gitignore",
    "chars": 78,
    "preview": ".next\n.now\n.env\n.env.*\nnode_modules\n*.log\n.DS_Store\n.vercel\npublic/sitemap.xml"
  },
  {
    "path": "website/.prettierignore",
    "chars": 54,
    "preview": "node_modules\n.next\nyarn.lock\npackage-lock.json\npublic\n"
  },
  {
    "path": "website/README.md",
    "chars": 823,
    "preview": "# Formik Docs\n\nThis is source code to formik.org. It is built with:\n\n- Next.js\n- MDX\n- Tailwind\n- Algolia\n- Notion\n\n## R"
  },
  {
    "path": "website/next-env.d.ts",
    "chars": 201,
    "preview": "/// <reference types=\"next\" />\n/// <reference types=\"next/image-types/global\" />\n\n// NOTE: This file should not be edite"
  },
  {
    "path": "website/next.config.js",
    "chars": 1417,
    "preview": "const webpack = require('webpack');\nconst fs = require('fs');\nconst path = require('path');\nconst visit = require('unist"
  },
  {
    "path": "website/package.json",
    "chars": 2841,
    "preview": "{\n  \"name\": \"fdocs3\",\n  \"version\": \"1.0.0\",\n  \"main\": \"index.js\",\n  \"author\": \"Jared Palmer <jared@palmer.net>\",\n  \"lice"
  },
  {
    "path": "website/postcss.config.js",
    "chars": 104,
    "preview": "// postcss.config.js\nmodule.exports = {\n  plugins: {\n    tailwindcss: {},\n    autoprefixer: {},\n  },\n};\n"
  },
  {
    "path": "website/public/robots.txt",
    "chars": 23,
    "preview": "User-agent: *\nDisallow:"
  },
  {
    "path": "website/scripts/build-sitemap.js",
    "chars": 462,
    "preview": "const sitemap = require('nextjs-sitemap-generator');\nconst fs = require('fs');\n\n// This is needed for the plugin to work"
  },
  {
    "path": "website/src/blog/formik-3-alpha.md",
    "chars": 6208,
    "preview": "---\ntitle: Formik 3 Alpha\ndate: October 27, 2020\npublished: true\nslug: formik-3-alpha\nauthors:\n  - Jared Palmer\npreview:"
  },
  {
    "path": "website/src/blog/new-docs.md",
    "chars": 12330,
    "preview": "---\ntitle: New Docs\ndate: June 30, 2020\npublished: true\nslug: new-docs\npreview: |\n  After a few weeks of work, I'm excit"
  },
  {
    "path": "website/src/components/ArrowRight.tsx",
    "chars": 404,
    "preview": "import * as React from 'react';\n\nexport function ArrowRight({ fill = '#718096', width = 6, height = 10 }: any) {\n  retur"
  },
  {
    "path": "website/src/components/Banner.tsx",
    "chars": 92,
    "preview": "import { ExternalLink } from './ExternalLink';\n\nexport function Banner() {\n  return null;\n}\n"
  },
  {
    "path": "website/src/components/Container.tsx",
    "chars": 320,
    "preview": "import * as React from 'react';\nimport cn from 'classnames';\nimport { HTMLProps } from 'react';\n\nexport const Container:"
  },
  {
    "path": "website/src/components/DocsPageFooter.tsx",
    "chars": 3277,
    "preview": "import NextLink from 'next/link';\nimport { useRouter } from 'next/router';\nimport * as React from 'react';\nimport { site"
  },
  {
    "path": "website/src/components/ExternalLink.tsx",
    "chars": 154,
    "preview": "import * as React from 'react';\n\nexport function ExternalLink(props: any) {\n  return <a {...props} rel=\"noopener\" target"
  },
  {
    "path": "website/src/components/Footer.tsx",
    "chars": 8657,
    "preview": "import * as React from 'react';\nimport Link from 'next/link';\nimport { ExternalLink } from './ExternalLink';\nimport { Fo"
  },
  {
    "path": "website/src/components/FormiumLogo.tsx",
    "chars": 7931,
    "preview": "import * as React from 'react';\n\nexport const FormiumLogo: React.FC<React.JSX.IntrinsicElements['svg']> = props => {\n  r"
  },
  {
    "path": "website/src/components/Highlight2.tsx",
    "chars": 3561,
    "preview": "import * as React from 'react';\nimport Highlight, { defaultProps } from 'prism-react-renderer';\nimport { TWButton } from"
  },
  {
    "path": "website/src/components/LayoutDocs.tsx",
    "chars": 6105,
    "preview": "import * as React from 'react';\nimport { MDXProvider } from '@mdx-js/react';\nimport { Banner } from 'components/Banner';"
  },
  {
    "path": "website/src/components/Logo.tsx",
    "chars": 12676,
    "preview": "import * as React from 'react';\n\nexport function Logo() {\n  return (\n    <svg\n      xmlns=\"http://www.w3.org/2000/svg\"\n "
  },
  {
    "path": "website/src/components/MDXComponents.tsx",
    "chars": 475,
    "preview": "import * as React from 'react';\nimport dynamic from 'next/dynamic';\nimport Image from 'next/image';\nimport Head from 'ne"
  },
  {
    "path": "website/src/components/Nav.tsx",
    "chars": 7542,
    "preview": "import Link from 'next/link';\nimport { useRouter } from 'next/router';\nimport * as React from 'react';\nimport { siteConf"
  },
  {
    "path": "website/src/components/ReactionForm.tsx",
    "chars": 2649,
    "preview": "import va from '@vercel/analytics';\nimport cn from 'classnames';\nimport { useRouter } from 'next/router';\nimport * as Re"
  },
  {
    "path": "website/src/components/Search.tsx",
    "chars": 5215,
    "preview": "import * as React from 'react';\nimport { createPortal } from 'react-dom';\nimport Router from 'next/router';\nimport Link "
  },
  {
    "path": "website/src/components/Seo.tsx",
    "chars": 2254,
    "preview": "import React from 'react';\nimport Head from 'next/head';\nimport { useRouter } from 'next/router';\n\nexport interface SeoP"
  },
  {
    "path": "website/src/components/Sidebar.tsx",
    "chars": 1386,
    "preview": "import { useState } from 'react';\nimport cn from 'classnames';\nimport { Search } from './Search';\n\nexport const Sidebar:"
  },
  {
    "path": "website/src/components/SidebarCategory.tsx",
    "chars": 3212,
    "preview": "import { useRef, useState, useEffect } from 'react';\nimport cn from 'classnames';\nimport { FiChevronDown } from 'react-i"
  },
  {
    "path": "website/src/components/SidebarHeading.tsx",
    "chars": 589,
    "preview": "import * as React from 'react';\n\nexport const SidebarHeading: React.FC<{\n  title: string;\n  children: React.ReactNode;\n}"
  },
  {
    "path": "website/src/components/SidebarMobile.tsx",
    "chars": 3209,
    "preview": "import * as React from 'react';\n\nimport {\n  disableBodyScroll,\n  enableBodyScroll,\n  clearAllBodyScrollLocks,\n} from 'bo"
  },
  {
    "path": "website/src/components/SidebarNavLink.tsx",
    "chars": 1909,
    "preview": "import * as React from 'react';\nimport Link from 'next/link';\nimport { useRouter } from 'next/router';\nimport cn from 'c"
  }
]

// ... and 50 more files (download for full content)

About this extraction

This page contains the full source code of the jaredpalmer/formik GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 250 files (1.4 MB), approximately 520.0k tokens, and a symbol index with 203 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!