Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Formik is a popular open-source library for building forms in React and React Native. It helps with handling form state, validation, and submission. Formik provides a simple and efficient way to create controlled form components with less boilerplate code.
Form State Management
Formik simplifies form state management by providing 'initialValues' to set up the form state and 'onSubmit' to handle form submission.
{"<Formik initialValues={{ name: '' }} onSubmit={(values) => { console.log(values); }}><Form><Field name='name' type='text' /><button type='submit'>Submit</button></Form></Formik>"}
Validation and Error Handling
Formik provides a 'validate' function to define custom validation logic and uses 'ErrorMessage' to display validation errors.
{"<Formik initialValues={{ email: '' }} 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); }}><Form><Field name='email' type='email' /><ErrorMessage name='email' component='div' /><button type='submit'>Submit</button></Form></Formik>"}
Integration with Yup for Schema Validation
Formik can be integrated with Yup, a schema builder for value parsing and validation, to simplify form validation using a schema.
{"<Formik initialValues={{ email: '' }} validationSchema={Yup.object({ email: Yup.string().email('Invalid email address').required('Required'), })} onSubmit={(values, { setSubmitting }) => { setTimeout(() => { alert(JSON.stringify(values, null, 2)); setSubmitting(false); }, 400); }}><Form><Field name='email' type='email' /><ErrorMessage name='email' /><button type='submit'>Submit</button></Form></Formik>"}
Custom Input Components
Formik allows the use of custom input components with the 'as' prop in the 'Field' component, enabling the creation of reusable form elements.
{"<Formik initialValues={{ name: '' }} onSubmit={(values) => { console.log(values); }}><Form><Field name='name' as={MyCustomInput} /><button type='submit'>Submit</button></Form></Formik>"}
React Hook Form is a library for managing forms in React. It uses hooks for form state management and is optimized for performance by minimizing the number of re-renders. Compared to Formik, React Hook Form is often considered faster due to its leaner API and focus on reducing re-renders.
Redux Form leverages Redux for form state management. It integrates tightly with Redux and allows form state to be stored in the Redux store. Compared to Formik, Redux Form is more suitable for applications that already use Redux and require complex form state management across multiple components.
Final Form is a framework-agnostic form library that can be used with React via 'react-final-form'. It focuses on performance and flexibility, offering subscription-based form state management. Compared to Formik, Final Form provides more fine-grained control over form state updates and subscriptions.
Let's face it, forms are really really verbose in React. To make matters worse, most form helpers do wayyyyy too much magic and often have a significant performace cost. Formik is minimal a Higher Order Component that helps you with the 3 most annoying parts:
Lastly, Formik helps you stay organized by colocating all of the above plus your submission handler in one place. This makes testing, refactoring, and reasoning about your forms a breeze.
Add Formik and Yup to your project. Formik uses Yup, which is like Joi, for schema validation.
npm i formik yup --save
Formik will inject the following into your stateless functional form component:
values: object
- Your form's valueserrors: object
- Validation errors, keys match values object shape exactly.error: any
- A top-level error object, can be whatever you need.onSubmit: (e: React.FormEvent<HTMLFormEvent>) => void
- Submit handler. This should be passed to <form onSubmit={onSubmit}>...</form>
onReset: () => void
- Reset handler. This should be passed to <button onClick={onReset}>...</button>
isSubmitting: boolean
- Submitting state. Either true or false.onChange: (e: React.ChangeEvent<any>) => void
- General onChange event handler. This will update the form value according to an <input/>
's name
attribute.onChangeValue: (name: string, value: any) => void
- Custom onChange handler. Use this when you have custom inputs (e.g. react-autocomplete). name
should match the form value you wish to update.Imagine you want to build a form that lets you edit user data. However, your user API has nested objects like so.
{
id: string,
email: string,
social: {
facebook: string,
twitter: string,
....
}
}
When we are done we want our form to accept just a user
prop and that's it.
// User.js
import React from 'react';
import Dialog from 'MySuperDialog';
import EditUserForm from './EditUserForm';
const EditUserDialog = ({ user }) =>
<Dialog>
<EditUserForm user={user} />
</Dialog>;
Enter Formik.
// EditUserForm.js
import React from 'react';
import Formik from 'formik';
import Yup from 'yup';
// Formik is a Higher Order Component that wraps a React Form. Mutable form values
// are injected into a prop called `values`. Additionally, Formik injects
// a single onChange handler that you can use on every input. You also get
// onSubmit, errors, and isSubmitting for free. This makes building custom
// inputs easy.
const SimpleForm = ({ values, onChange, onSubmit, onReset, errors, error isSubmitting, }) =>
<form onSubmit={onSubmit}>
<input
type="text"
name="email"
value={values.email}
onChange={onChange}
placeholder="john@apple.com"
/>
{errors.email && <div>{errors.email}</div>}
<input
type="text"
name="facebook"
value={values.facebook}
onChange={onChange}
placeholder="facebook username"
/>
{errors.facebook && <div>{errors.facebook}</div>}
<input
type="text"
name="twitter"
value={values.twitter}
onChange={onChange}
placeholder="twitter username"
/>
{errors.twitter && <div>{errors.twitter}</div>}
{error && error.message && <div style={{color: 'red'}}>Top Level Error: {error.message}</div>}
<button onClick={onReset}>Reset</button>
<button type="submit" disabled={isSubmitting}>Submit</button>
</form>;
// Now for the fun part. We need to tell Formik how we want to validate,
// transform props/state, and submit our form.
export default Formik({
// Give our form a name for debugging in React DevTools
displayName: 'SimpleForm',
// Define our form's validation schema with Yup. It's like Joi, but for
// the browser.
validationSchema: Yup.object().shape({
email: Yup.string().email().required(),
twitter: Yup.string(),
facebook: Yup.string(),
}),
// We now map React props to form values. These will be injected as `values` into
// our form. (Note: in the real world, you would destructure props, but for clarity this is
// not shown)
mapPropsToValues: props => ({
email: props.user.email,
twitter: props.user.social,
facebook: props.user.facebook,
}),
// Sometimes your API needs a different object shape than your form. Formik let's
// you map `values` back into a `payload` before they are
// passed to handleSubmit.
mapValuesToPayload: values => ({
email: values.email,
social: {
twitter: values.twitter,
facebook: values.facebook
},
}),
// Formik lets you colocate your submission handler with your form.
// In addition to the payload (the result of mapValuesToPayload), you have
// access to all props and some stateful helpers.
handleSubmit: (payload, { props, setError, setSubmitting }) => {
// do stuff with your payload
// e.preventDefault(), setSubmitting, setError(undefined) are called before handle submit is. so you don
CallMyApi(props.user.id, payload)
.then(
res => {
setSubmitting(false)
// do something to show success
// MyToaster.showSuccess({ message: 'Success!' })
},
err => {
setSubmitting(false)
setError(err)
// do something to show a rejected api submission
// MyToaster.showError({ message: 'Shit!', error: err })
}
)
},
})(SimpleForm);
FAQs
Build forms in React, without the tears
The npm package formik receives a total of 2,015,617 weekly downloads. As such, formik popularity was classified as popular.
We found that formik demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.