Build forms in React, without the tears 😭

Issues
  • Formik does not re-render when initialValues change

    Formik does not re-render when initialValues change

    Current Behavior

    If there is an "external" component controlling initialValues passed to Formik, Formik never updates it. This may be desired behavior, however in my specific case I need to re-render the form (and ideally, warn the user about unsaved changes) with new initialValues. If this is not a bug, any ideas on how to achieve this?

    Steps to Reproduce

    1. Open https://codesandbox.io/s/kworjlq7n3
    2. Toggle between the select options
    3. You will see that all components in the chain re-render with new values, however Formik render never changes initialValues.

    Expected behavior

    When initialValues change, Formik should trigger a re-render and provide new initialValues in its render method.

    CodeSandbox Link: https://codesandbox.io/s/kworjlq7n3

    EDIT: CodeSandbox demonstrates a working solution


    • Formik Version: 1.0.2
    • React Version: 16.3.2
    • TypeScript Version: N/A
    • Browser and Version: Chrome Version 68.0.3440.84 (Official Build) (64-bit)
    • OS: Mac OS 10.13.4
    Focus: Documentation Component: Formik 
    opened by iamvanja 97
  • How to avoid rerendering?

    How to avoid rerendering?

    Question

    Hello!

    Formik library have built-in tools to avoid rerendering all form fields, after changing one of this fields?

    Resolution: Duplicate Type: Enhancement in progress 
    opened by SuperOleg39 78
  • [v2] Hooks

    [v2] Hooks

    Improvements

    • [x] Create <Field as> prop (#1406)
    • [x] Add meta prop to <Field children> (#1406)
    • [x] Break out useFormik from <Formik>
    • [x] onReset and handleReset tests
    • [x] async onSubmit (no more setSubmitting(false) needed)
    • [x] Make validation cancellable (#1026, #671)
    • [x] useField's second element is field metadata (#343)
    • [x] Add initialErrors, initialTouched, initialStatus (#1410)
    • [x] Fix isValid (#1410)
    • [ ] <Field >'s uses handleBlur('path') and handleChange('path') override (#1113)
    • [x] Upgrade to TypeScript 3.5 and React 16.9 (#1559)

    Breaking Changes

    • Breaking TypeScript change: FormikActions have been renamed to FormikHelpers
    • Formik no longer uses console.error in its warnings, but rather console.warn

    Deprecations

    These are just warnings for now.

    • [x] <Field render> (#1406)
    • [x] <Field component> (#1406)
    • [x] isInitialValid and fix isValid (#1410)

    Documentation

    • [ ] useField
    • [ ] "Creating your own <FieldGroup>"
    • [ ] Checkboxes and Radio inputs
    • [ ] <FormikConsumer>
    • [ ] useFormikContext
    • [ ] useFormik
    • [ ] Rewrite examples with hooks
    • [ ] Rewrite tutorial with hooks
    • [ ] Migration Guide
    • [ ] Blog post

    Feel free to start making PR's to this branch. This is going to take a minute to figure out as there are a LOT of new paradigms.

    #1046 #1005

    opened by jaredpalmer 67
  • Added nested values proposal prototype (#202)

    Added nested values proposal prototype (#202)

    This is my quick suggestion to solve issue #202 . It is far from perfect (I don't use Typescript so I neglected types), also, I couldn't make lodash/fp working with Typescript, so I needed to use mutable _.set, and sadly I used it with deepClone. Of course this would need to be refactored, but this is just a prototype.

    If you like this idea, we could work on it more, add missing tests etc.

    The good news is, that all tests are passing so it is backward compatible change :)

    Type: Enhancement in progress 
    opened by klis87 62
  • setFieldValue should return a Promise or receive a callback

    setFieldValue should return a Promise or receive a callback

    Feature

    Current Behavior

    setFieldValue() is async because it uses setState(), but it doesn't receive a callback or return anything. That's why it's hard to get modified values right after that, for example if I want to run submitForm().

    Desired Behavior

    setFieldValue() will return a promise, so I could await it and get changed values.

    Suggested Solutions

    return a Promise from setFieldValue() OR add additional callback to function declaration

    • Formik Version: 0.11.11
    • React Version: 16.2.0
    • CodeSandbox Link: https://codesandbox.io/s/x9445yl5lp
    Type: Enhancement Priority: Medium 
    opened by today- 60
  • Initial validation or initialErrors prop

    Initial validation or initialErrors prop

    What if the user has set some field values, and we do store them somewhere, and when the user returns to the app those values are invalid. Is there no way to run validate on initialization?

    Type: Enhancement Priority: Medium 
    opened by morgs32 44
  • v2.0 Umbrella Issue

    v2.0 Umbrella Issue

    • [ ] Hooks (#1063)
    • [ ] Use JSX generics on <Field<Values>> (#726 , #370)
    • [ ] Add debugger / logger
    • [ ] Begin deprecating dirty, with warning (replaced withisDirty) (#353)
    • [ ] Add submitAttemptCount, submitFailureCount, submitSuccessCount and computed boolean counters? didSubmitSucceed and didSubmitFail or submitFailure / submitSuccess
    • [ ] Add warnings, setFieldWarning, setWarnings (#1001, #389)
    • [x] Async onSubmit (#486 , #500)
    • [x] Ensure that Formik context value is immutable
    • [ ] Promisify or give callbacks to all setFieldXXX functions
    pinned v2 
    opened by jaredpalmer 43
  • Extend setValue functionality

    Extend setValue functionality

    Formik is great, but there are one or two parts where the methods could be a little more TypeScript friendly, and in this PR I'm introducing a new method which I hope takes a step in this direction.

    For context: I have a form where a user can enter an ID into a field to perform a lookup. Data is fetched over HTTP, and I use data from the response to populate other form fields by using multiple setFieldValue calls. The signature of setFieldValue isn't type-safe – the value is any, and the field may not necessarily exist. (There was some discussion of this in #1388)

    This PR introduces a setFieldValues method that takes a Partial<Values> and merges that with the existing form values. I would find this really useful.

    Things that I'm not too sure about, and that I'd welcome feedback on:

    • Does this method go against the design of Formik, where fields are referenced using the path-style string (eg. people.0.first_name)?
    • Is there a better name for this method, than setFieldValues? It's basically like setValues, but it allows subsets and merges rather than overwriting.
    Type: Enhancement stale 
    opened by samstarling 43
  • Using styled components with formik is incredibly slow

    Using styled components with formik is incredibly slow

    I'm just playing with formik library and found performance issue with custom component in Field tag when the custom component uses styled components heavily.

    When I keep pressing the key in an input box which is wrapped in multiple hierarchy of styled components, it causes huge lagging but instead of that, if I use simple divs, it is comparatively faster.

    Type: Question done 
    opened by mjangir 43
  • How does yup's trim work?

    How does yup's trim work?

    I tried adding trim() to my formik validation schema:

    Yup.object().shape({
        label: Yup.string().trim().required('some error msg'),
    });
    

    But the field value is not being trimmed.

    opened by sketchbuch 42
  • Make automatically setting isSubmitting to false optional

    Make automatically setting isSubmitting to false optional

    Feature request

    Current Behavior

    When using Formik with an asynchronous submit handler, isSubmitting is automatically set to false after the handler resolves (according to the important note here). When unmounting the component within the submit handler (e.g. because submission was successful and we can close the form / navigate away), Formik tries to set isSubmitting to false resulting in a React warning

    Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

    Desired Behavior

    It would be great to optionally tell Formik not to set isSubmitting automatically. Also this guideline should reflect the different behavior depending on the submit handler being synchronous or asynchronous.

    Suggested Solution

    A possible solution would be to add an optional FormikProp disableAutomaticIsSubmittingChange (there's probably a better name for that). By making it an optional prop without changing the previous behavior when omitting it, it wouldn't be a breaking change. Usage would be like this:

    <Formik
      onSubmit={async (values, formikBag) => {/* some async handling here */}}
      disableAutomaticIsSubmittingChange
      ...
    >
      ...
    </Formik>
    

    Who does this impact? Who is this for?

    Everybody who is unmounting the component after submission.

    Describe alternatives you've considered

    Either ignore the console error or use setTimeout within the handler to delay the unmounting so that the component is still mounted when Formik sets isSubmitting.

    Type: Feature Request 
    opened by tobiaswaltl 0
  • Add handler for failed validations only for submit attempts

    Add handler for failed validations only for submit attempts

    Feature request

    Current Behavior

    There is no way to execute custom code on validation failure if and only if the validation was requested by submit attempt.

    Desired Behavior

    Have a callback that is executed when user tries to submit a form and validation fails.

    Suggested Solution

    add e.g. onSubmitFailure to FormikConfig interface.

    Who does this impact? Who is this for?

    Example situation: I have a multi-tabbed form. When user attempts to submit it and validations fail, I want to switch the user to first tab containing errors. But this should not happen inside the validation handler in case some other feature triggered the validation.

    Describe alternatives you've considered

    This is hard to solve in any other reasonable way. This should be an imperative reaction on the submit attempt, just like regular onSubmit handle. Any other solution that I can imagine would involve some dirtiness.

    Type: Feature Request 
    opened by richard-ejem 0
  • Formik enters into an endless validation loop when validateOnMount is activated and initialValues change

    Formik enters into an endless validation loop when validateOnMount is activated and initialValues change

    Bug report

    Current Behavior

    When using Formik with validateOnMount: true and mutated initialValues controlled outside the form context, on the 1st change, Formik will go into an infinite validation loop, crashing the page eventually. This behavior is easily caught when using a toggle in the form that affects its validation and/or structure.

    Expected behavior

    It is expected that, whenever initialValues change, a proper validation is done on the newly provided values.

    Reproducible example

    Formik validateOnMount with a toggle that freezes the app: https://codesandbox.io/s/github/rapzo/formik-validateOnMount/tree/csb-dengj

    A possible workaround, although it kind of limits the depth of the changeable value: https://codesandbox.io/s/github/rapzo/formik-validateOnMount/tree/main

    Suggested solution(s)

    https://github.com/formium/formik/compare/master...rapzo:patch-1

    Additional context

    I don't know if this was an expected behavior so I'm creating the issue before a PR. Will be happy to add test cases to the PR if this proposal makes sense.

    Your environment

    | Software | Version(s) | | ---------------- | ---------- | | Formik | 2.2.9 | React | 17.0.2 | TypeScript | 4.4.2 | Browser | Google Chrome 91.0.4472.164 (Official Build) (64-bit) | npm/Yarn | 6.14.15/1.22.11 | Operating System | Manjaro (kernel: 5.10.56-1-MANJARO)

    Type: Bug 
    opened by rapzo 1
  • Update users.ts

    Update users.ts

    null

    opened by bookingjini 2
  • Relative links in docs aren't working

    Relative links in docs aren't working

    Bug report

    Current Behavior

    Several links in the docs are written in the *.md files as relative paths to other markdown files. Right-clicking and selecting "Open in a new tab" works on these links as expected. However, simply left-clicking on the link causes problems.

    For example, look at docs/api/fieldarray.md:

    If you use [`validationSchema`](./formik.md#validationschema-schema-schema) and your...
    

    This is what it looks like when you hover over it in the docs: image

    Clicking it will bring you here: image

    I've already described a similar issue in #3202

    Expected behavior

    The links should work without an error when you click on them

    Reproducible example

    See the "Current Behavior" section above.

    Suggested solution(s)

    As I mentioned in #3202, I think the error is caused by NextJS treating the relative directory as an absolute directory. Would it work to just replace all these links with absolute directories? I don't use NextJS, so I don't know.

    Additional context

    None

    Your environment

    | Software | Version(s) | | ---------------- | ---------- | | Formik | N/A | React | N/A | TypeScript | N/A | Browser | Firefox and Chrome | npm/Yarn | N/A | Operating System | Windows 10

    Type: Bug 
    opened by ChrisCrossCrash 0
  • Sequential setFieldValue runs validation incorrectly

    Sequential setFieldValue runs validation incorrectly

    Bug report

    Current Behavior

    User has three fields. "fillFields", "firstName", "lastName". fill - is a radio button. When user clicks on this fields both another fields are filling some values. Filling of this values happen in useEffect hook. And all works fine without validation. It doesn't work properly.

    I have the example. https://codesandbox.io/s/red-glade-x3y32 Step to reproduce this bug:

    1. Fill firstName
    2. Fill lasName
    3. Clear firstName
    4. Clear lastName
    5. You see the errors about requirement fields above
    6. Click to radio button "Fill fields"
    7. The error one of field is cleared, but the error second field still display to user

    Then if i click outside fillFields. Validation runs again after onBlur and the error disappears. But it has to disappear after onChange. The validation needs to call after updating of values state.

    Expected behavior

    The errors doesn't appear to user for all fields.

    Reproducible example

    https://codesandbox.io/s/red-glade-x3y32?file=/src/App.js

    Additional context

    I use useFormik hook. I suppose validation doesn't has to run before the state was updated.

    Your environment

    | Software | Version(s) | | ---------------- | ---------- | | Formik | 17.0.2 | React | 2.2.9 | Operating System | Any

    Type: Bug ready to land 
    opened by WebTravel 3
  • Touched state when using FieldArrays

    Touched state when using FieldArrays

    Bug report

    The ISSUE

    Im running into an issue displaying validation errors for FieldArrays using Formik and Yup.

    Ideally, to provide a good user experience we would want to show errors related to a field only when the field has been touched by the user, and while this is quite easy to accomplish with normal fields, Im struggling to mimic the behaviour for FieldArrays.

    The reality is that for FieldArrays the β€˜touched’ state doesn’t match up well with the way errors can be raised by YUP validations.

    There are two issues:

    1. Formik will only manage the 'touched' state of items within the array but not the array itself so if you had a validation on the min and max amount of items on the array and the user removed all the items there will be no touched state for the array, but there will be an error.

    2. FieldArray helpers dont update the touched state of an array when either 'pushing' or 'removing' items from the array.

    The below is an example which demonstrates the above two issues:

    With the following schema we expect there to be at least 1 item within β€˜someArray’ but no more than 5 items.

        Yup.object({
            someArray: Yup.array().min(1).max(5)
        })
    

    Imagine the following initial formik state, at this point we wouldn’t want to show the someArray error because nothing has been touched.

        initialValues: {
            someArray: []
        },
        values: {
            someArray: []
        },
        errors: {
            someArray: β€˜At least 1 item should be in this array’
        },
        touched: {}
    

    If I β€˜push’ and item to someArray, then it will not longer be an error and I would expect the following state:

        initialValues: {
            someArray: []
        },
        values: {
            someArray: ['item']
        },
        errors: {
            someArray: undefined
        },
        touched: {
            someArray: [true]
        }
    

    Unfortunately when using the FieldArray helpers the 'touched' state isnt updated, so the actual state we would get is:

        initialValues: {
            someArray: []
        },
        values: {
            someArray: ['item']
        },
        errors: {
            someArray: undefined
        },
        touched: {}
    

    If I 'remove' the item added now, then the error will return and I would expect the following state:

        initialValues: {
            someArray: []
        },
        values: {
            someArray: []
        },
        errors: {
            someArray: β€˜At least 1 item should be in this array’
        },
        touched: {
            someArray: true
        }
    

    Unfortunately again the FieldArray helpers don't update the 'touched' state. As a result this error wont be shown to the user (provided im only showing the error is the field was touched)

        initialValues: {
            someArray: []
        },
        values: {
            someArray: []
        },
        errors: {
            someArray: β€˜At least 1 item should be in this array’
        },
        touched: {}
    

    Expected behavior

    • FieldArray helpers should update the touched state of an array
    • Should all items be removed from an array the touched state should be array: true

    Reproducible example

    https://codesandbox.io/s/upbeat-shamir-hmiwq?file=/src/Users.tsx

    Your environment

    | Software | Version(s) | | ---------------- | ---------- | | Formik | 2.2.9 | React | 17.0.2 | TypeScript | 4.3.5 | Browser | Chrome | npm/Yarn | Yarn | Operating System | macOs Catalina 10.15.7

    Type: Bug 
    opened by james-portelli-cko 0
  • Formik in not working with react apps created with webpack

    Formik in not working with react apps created with webpack

    I've created a React App from scratch like this article https://dev.to/youssefzidan/creating-react-application-with-webpack-2i4h

    and Formik is not working at all with this approach.

    Type: Bug 
    opened by YoussefZidan 2
  • [Reopen] Let promise rejection propagate in handleSubmit

    [Reopen] Let promise rejection propagate in handleSubmit

    Resolve #2758

    Reopening #3052

    opened by JoseLion 2
  • FieldArray performance issue for large data

    FieldArray performance issue for large data

    I have array of objects and it is maintained by using FieldArray, in 0th index performance is fine but when index increases performance is decreased.

    opened by Sushmasrig 0
Owner
Formium
The headless form builder for the modern web. Creators of Formik.
Formium
πŸ“‹ React Hooks for forms validation (Web + React Native)

Version 7 | Version 6 Features Built with performance and DX in mind Embraces native form validation Out of the box integration with UI libraries Smal

React Hook Form 23.2k Sep 23, 2021
A React component for building Web forms from JSON Schema.

react-jsonschema-form A simple React component capable of using JSON Schema to declaratively build and customize web forms. Explore the docs Β» View Pl

null 10.6k Sep 22, 2021
JavaScript Survey and Form Library

SurveyJS is a JavaScript Survey and Form Library. SurveyJS is a modern way to add surveys and forms to your website. It has versions for Angular, jQue

SurveyJS 3k Sep 16, 2021
A Higher Order Component using react-redux to keep form state in a Redux store

redux-form You build great forms, but do you know HOW users use your forms? Find out with Form Nerd! Professional analytics from the creator of Redux

Redux Form 12.6k Sep 24, 2021
:fire: A highly scalable, offline-first foundation with the best developer experience and a focus on performance and best practices.

Start your next react project in seconds A highly scalable, offline-first foundation with the best DX and a focus on performance and best practices Cr

react-boilerplate 27.9k Sep 20, 2021
A Foundation for Scalable Cross-Platform Apps

Electron React Boilerplate uses Electron, React, React Router, Webpack and React Fast Refresh. Install If you have installation or compilation issues

Electron React Boilerplate 18.2k Sep 16, 2021
React bindings for MobX

mobx-react ?? ?? ?? This repo has been moved to mobx Package with React component wrapper for combining React with MobX. Exports the observer decorato

MobX 4.8k Sep 24, 2021
Seamless mapping of class names to CSS modules inside of React components.

React CSS Modules React CSS Modules implement automatic mapping of CSS modules. Every CSS class is assigned a local-scoped identifier with a global un

Gajus Kuizinas 5.2k Sep 17, 2021
Framework-agnostic CSS-in-JS with support for server-side rendering, browser prefixing, and minimum CSS generation

Aphrodite Framework-agnostic CSS-in-JS with support for server-side rendering, browser prefixing, and minimum CSS generation. Support for colocating y

Khan Academy 5.2k Sep 16, 2021
Selector library for Redux

Reselect Simple β€œselector” library for Redux (and others) inspired by getters in NuclearJS, subscriptions in re-frame and this proposal from speedskat

Redux 18.2k Sep 15, 2021
Set up a modern web app by running one command.

Create React App Create React apps with no build configuration. Creating an App – How to create a new app. User Guide – How to develop apps bootstrapp

Facebook 90.4k Sep 24, 2021
A simple, declarative, and composable way to fetch data for React components

React Refetch A simple, declarative, and composable way to fetch data for React components. Installation Requires React 0.14 or later. npm install --s

Heroku 3.4k Sep 24, 2021
Get started with React, Redux, and React-Router.

Deprecation Warning This project was started at the advent of the Redux ecosystem, and was intended to help users get up and running quickly. Since th

David Zukowski 10.4k Sep 18, 2021
Ruthlessly simple bindings to keep react-router and redux in sync

Project Deprecated This project is no longer maintained. For your Redux <-> Router syncing needs with React Router 4+, please see one of these librari

React Community 7.9k Sep 20, 2021
:rocket: Blazing fast page load and seamless navigation.

React Server is now defunct Consider Next.js instead. React Server React framework with server render for blazing fast page load and seamless transiti

Redfin 3.9k Sep 11, 2021
Predictable state container for JavaScript apps

Redux is a predictable state container for JavaScript apps. (Not to be confused with a WordPress framework – Redux Framework) It helps you write appli

Redux 56.7k Sep 21, 2021
A starter boilerplate for a universal webapp using express, react, redux, webpack, and react-transform

React Redux Universal Hot Example About This is a starter boilerplate app I've put together using the following technologies: Isomorphic Universal ren

Erik Rasmussen 12.1k Sep 20, 2021
Declarative routing for React

React Router Declarative routing for React Docs View the docs here Migrating from 2.x/3.x? 3.x docs 2.x docs Packages This repository is a monorepo th

React Training 44k Sep 19, 2021
Isomorphic flux implementation

alt Check out the API Reference for full in-depth docs. For a high-level walk-through on flux, take a look at the Getting Started guide. What follows

Josh Perez 3.5k Sep 7, 2021