Easily develop higher-quality react forms with Formik (iv) several other API parsing

Source: Internet
Author: User
Tags i18n

(The following section is in the translation, please wait ... ) <field/>

<field/> would automagically hook up inputs to formik. It uses the name attribute to match up with Formik state. <field/> Would default to an <input/> element. To change the underlying element of <field/> Specify a component prop. It can either is a string like select or another React component. <field/> can also take a render prop.

Import React from ' React '; import {formik, Field} from ' Formik '; const Example = () = (<div> 
Validate?: (value:any) = undefined | string | Promise<any>

You can run independent field-level validations by passing a function to the validate prop. The function would respect the Validateonblur and Validateonchange config/props specified in the <Field> ' s parent < ; Formik>/Withformik. This function can is either be:

Synchronous and if invalid, return a string containing the error message or return undefined.

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

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

Asynchronous and return a Promise that ' s error was an A string with the error message

// Async validation for Fieldconst sleep = ms => new Promise(resolve => setTimeout(resolve, ms));const validate = value => {  return sleep(2000).then(() => {    if ([‘admin‘, ‘null‘, ‘god‘].includes(value)) {      throw ‘Nice try‘;    }  });};

Note:to allow for i18n libraries, the TypeScript typings for validate is slightly relaxed and allow your to return a Func tion (e.g. i18n (' invalid ')).

Refs

When you aren't using a custom component and you need to access the underlying DOM node created by Field (e.g. to call fo CUS), pass the callback to the Innerref prop instead.

<fieldarray/>

<fieldarray/> is a component this 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/> would then give the access to array helper methods via render props. For convenience, calling these methods would trigger validation and also manage touched for you.

Import React from ' React '; import {formik, Form, Field, Fieldarray} from ' formik ';//Here's an example of a Form with an Editable list.//Next to each input was buttons for insert and remove.//If the list was empty, there is a button to add a n Item.export Const Friendlist = () = (<div> 
Name:string

The name or path to the relevant key in values.

Validateonchange?: Boolean

Default is true. Determines if form validation should or should not is 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.prope Rty for the name attributes of <field/> or <input/> elements in <fieldarray/>.

<Form>  <FieldArray    name="friends"    render={arrayHelpers => (      <div>        {values.friends.map((friend, index) => (          <div key={index}>            <Field name={`friends[${index}]name`} />            <Field name={`friends.${index}.age`} /> // both these conventions do            the same            <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 tricky with <fieldarray>.

If you use Validationschema and your form have array validation requirements (like a min length) as well as nested array fi ELD requirements, displaying errors can be tricky. Formik/yup'll show validation errors inside out. For example,

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 has friends ' and ' Minimum of 3 friends ' (our example ' s array validation contstraints) ...

Bad
// within a `FieldArray`‘s renderconst FriendArrayErrors = errors =>  errors.friends ? <div>{errors.friends}</div> : null; // app will crash
Good

Within a FieldArray ' s render

const FriendArrayErrors = errors =>  typeof errors.friends === ‘string‘ ? <div>{errors.friends}</div> : null;

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

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 is added to Field and fieldarray that'll give you relevant metadata suc H as Error & Touch, which'll save you from have to use Formik or Lodash's getin or checking if the path is defined On your own.

Fieldarray Helpers

The following methods is 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 The 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 a array and return its length
    • Remove<t> (index:number): T | Undefined:remove an element at a index of an array and return it
    • Pop<t> (): T | Undefined:remove and return value from the end of the array**
Fieldarray Render Methods

There is three ways to render things with <fieldarray/>

<FieldArray name="..." component><FieldArray name="..." render>render: (arrayHelpers: ArrayHelpers) => React.ReactNodeimport React from ‘react‘;import { Formik, Form, Field, FieldArray } from ‘formik‘export const FriendList = () => (  <div>    
Component:React.ReactNode
import React from ‘react‘;import { Formik, Form, Field, FieldArray } from ‘formik‘export const FriendList = () => (  <div>    
<form/>

Like <field/> <form/> are a helper component you can use to save time. It is tiny wrapper around <form onsubmit={context.formik.handlesubmit}/>. This means you don ' t need to explictly type out <form onsubmit={props.handlesubmit}/> If you don ' t want to.

Reactdom only
import React from ‘react‘;import { Formik, Field, Form } from ‘formik‘;const Example = () => (  <div>    
Withformik (Options)

Create a Higher-order React component class that passes props and form handlers (the "Formikbag") into your component Deri Ved from supplied options.

Optionsdisplayname?: string

When your inner form component are a stateless functional component, you can use the DisplayName option to give the Compone NT a proper name so you can more easily find it in React DevTools. If specified, your wrapped form would show up as Formik (DisplayName). If omitted, it'll show up as Formik (Component). This option isn't 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 a deep equality).

Handlesubmit: (values:values, formikbag:formikbag) = void

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 (i.e. all, methods with names, start with set<thing> + Resetform), and any props, 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 is not included in the formikbag.

Isinitialvalid?: Boolean | (Props:props) = Boolean

Default is false. Control the initial value of IsValid prop prior to mount. You can also pass a function. Useful for situations if you want to enable/disable a submit and reset buttons on initial mount.

Mappropstovalues?: (props:props) = Values

If This option was specified, then formik would transfer its results to updatable form state and make these values Availab Le to the new component as props.values. If Mappropstovalues is isn't specified, then formik'll map all props that's not functions to the inner component ' s props . values. That's, if you omit it, Formik would 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-to validate your forms.

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

Synchronous and return an errors object.// Synchronous validationconst validate = (values, props) => {  let errors = {};  if (!values.email) {    errors.email = ‘Required‘;  } else if (!/^[A-Z0-9._%+-][email protected][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 error is an Errors object

// Async Validationconst sleep = ms => new Promise(resolve => setTimeout(resolve, ms));const validate = (values, props) => {  return sleep(2000).then(() => {    let errors = {};    if ([‘admin‘, ‘null‘, ‘god‘].includes(values.username)) {      errors.username = ‘Nice try‘;    }    // ...    if (Object.keys(errors).length) {      throw errors;    }  });};
Validateonblur?: Boolean

Default is true. Use the This option to the run validations on Blur events. More specifically, when either Handleblur, setfieldtouched, or settouched is called.

Validateonchange?: Boolean

Default is true. Use the This option to the tell Formik to run validations on the change events and change-related methods. More specifically, when either HandleChange, SetFieldValue, or setvalues is called.

Validationschema?: Schema | ((props:props) = Schema)

A Yup schema or a function that returns a Yup schema. This was used for validation. Errors is mapped by key to the inner component ' s Errors. Its keys should match those of values.

Injected props and methods

These is identical to the props of <formik render={props = ...}/>

Using Connect () in Formik

Connect () is a high-order component, that is injects raw formik context as prop called Formik into the inner component. Fun Fact:formik uses connect () under the hood to wire up <field/>, <fastfield>, and <form>. Advanced users could find it useful to use connect () when building custom components.

import { connect } from ‘formik‘;const SubmitCount = ({ formik }) => <div>{formik.submitCount}</div>;export default connect(SubmitCount);

Easily develop higher-quality react forms with Formik (iv) several other API parsing

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.