npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

formik-fields

v0.2.1

Published

An extension to the great formik-library

Downloads

35

Readme

FormikFields

An extension to the great formik-library.

Motivation

The main goal is to keep the simplicity of formik's <Field>-component and to remove the magic introduced by the implicit context and the name-string. In addition, when updating one field, you do not want to have to render all the others again.

Installation

FormikFields is available as an npm-package and has formik as peer-dependency:

yarn add formik formik-fields
# or npm
npm install formik formik-fields

Example

import * as React from 'react';
import { FormikFields } from 'formik-fields';
import { FormikFieldInput } from './your-custom-component';

interface MyFormValues {
  email: string;
  name: string;
}

export const MyForm = () => (
  <FormikFields<MyFormValues>
    fields={{
      name: {
        initialValue: '',
        validate: val => !val && 'Name should not be empty'
      },
      email: { initialValue: '' }
    }}
    onSubmit={(values: MyFormValues) => console.log(values)}
    render={(fields, formikBag) => (
      <form onSubmit={formikBag.handleSubmit}>
        <FormikFieldInput field={fields.email} />
        <FormikFieldInput field={fields.name} />
        <button type="submit">submit</button>
      </form>
    )}
  />
);

Table of Contents

<FormikFields>-API

The <FormikFields>-Component accepts following props:

fields

Type: { [fieldName]: FieldDefinition }

const formikFieldDefinition = {
  name: {
    initialValue: '',
    validate: val => !val && 'Name should not be empty'
  },
  email: { initialValue: '' }
};

FieldDefinition

| Name | Type | Description | | ----------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | initialValue (required) | Value | Initial value when the form is first mounted. | | validate | (val: Value) => any | If not falsy, the fields error-prop is set with the computed value from this function. See formik's How Form Submission Works to understand how validation works. |

render-prop

type: (fieldsState, formikProps) => ReactNode

You can also use the children-prop, for more usage about the render-prop-pattern head over the the react-documentation.

fieldsState

type : { [fieldName]: FieldState }

FieldState is an Object with following members:

| Name | Type | Description | | -------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | name | string | equal to the corresponding key in the fieldsState-Object | | value | FormValue[name] | current value, on mount equal to initialValue in the FieldDefinition | | isTouched | boolean (default: false) | result from setIsTouched or handleBlur | | error | any | result from the validate-function in the FieldDefinition | | setValue | (val: FormValue[name], shouldValidate = true) => void | set value and re-evaluate your validators, calls internally formik's setFieldValue | | setIsTouched | (isTouched: boolean, shouldValidate = true) => void | set isTouched and re-evaluate your validators, calls internally formik's setFieldTouched | | handleChange | (e: React.ChangeEvent) => void | calls setValue with the extracted value from an input-onChange-callback | | handleBlur | () => void | calls setIsTouched(true) |

formikProps

The second callback-parameter contains all props from Formik's render-prop-callback, visit their documentation for more information.

TypeScript

This project is written in TypeScript and so typings should always be up-to-date. You should always enhance the <FormikFields>-Component with your form-values-Interface (since TypeScript 2.9 you can do this inline):

interface MyFormValues {
  email: string;
  name: string;
}

export const MyForm = () => <FormikFields<MyFormValues> {/*...*/} />

Now your fields and render-prop-parameters are enhanced with your specific field-names and -types.

usage without TypeScript

You can use FormikFields as well as formik without TypeScript (via ES6-import or require). However, you lose the advantages of the types in your forms (with TS the fields are checked against the initial definitions of the form-values-structure and so you can only access defined fields).

advanced

custom input example

A minimum implementation of a FormikFieldInput in TypeScript could look like this:

import { PureComponent } from 'react';
import { FormikFieldState } from 'formik-fields';

interface FormikFieldInputProps {
  field: FormikFieldState<string>;
}

// Use React.PureComponent component to take advantage of the optimized fields
export class FormikFieldInput extends PureComponent<FormikFieldInputProps> {
  render() {
    const { field, ...props } = this.props;

    return (
      <div>
        <input
          onChange={field.handleChange}
          onBlur={field.handleBlur}
          value={field.value}
          {...props}
        />
        {field.isTouched && field.error && <div>({field.error})</div>}
      </div>
    );
  }
}

formik under the hood

Since this is only an extension, <FormikFields> accepts all props of the actual <Formik> component (except Component and initialValues, which is overwritten by your field-definitions).

When you define Formik's validate-prop, the results of the specifically defined validate function are merged with the results of the field-validations (where the specific validate function overwrites the values of the field-validations if they have the same keys).

Field-Validators and form-submission

If you define a field-level-validate-function via the FieldDefinition, the result of your function can prevent your form to submit:

If this function returns a falsy value, this field will not prevent your form to submit. Otherwise, the form validation corresponds to that of Formik, see How Form Submission Works in their documentation.

for advanced validations you can use formik's validate-prop

Validation and performance

your field-validator-function HAVE TO be always a pure function with only one parameter (the field-value itself). Under this assumption, the results of the validations are memoized. The fields are only renewed if there are actual changes. So you can use Reacts PureComponent to improve the performance of your forms.