We often encounter functional modules of form submission in Web projects, such as login, saving product information and other functions. There is a package called Formik that encapsulates a lot of the functionality we used to process forms in the React project.

Formik introduction

Install: NPM I formik

  1. Enhance form processing capability and simplify form processing process

Basic use of Formik

import { useFormik } from 'formik'

function App() {
	// Initialize the data
	const handleSubmit = values= > {
		// Values are the latest form data when the form is submitted
		console.log(values)
	}
	// initialValues is the initialized data
	const formik = useFormik({ initialValues: { username: 'zhangsan'.password: '123456' }, onSubmit: handleSubmit })
	return (
		// The form item in the form must correspond to the key of the initalValues object by name
		<form onSubmit={formik.handleSubmit}>
			<input type="text" name="username" value={formik.values.username} onChange={formik.handleChange} />
			<input type="password" name="password" value={formik.values.password} onChange={formik.handleChange} />
			<input type="submit" />
		</form>)}export default App
Copy the code

Form validation for FormIK

import { useFormik } from 'formik'
import * as Yup from 'yup'

function App() {
	// Initialize the data
	const handleSubmit = values= > {
		// Values are the latest form data when the form is submitted
		console.log('Verified:', values)
	}
	// initialValues is the initialized data
	const formik = useFormik({
		initialValues: { username: 'zhangsan'.password: '12' },

		// validate: values => {
		// const errors = {}
		// 	if (!values.username) {
		// errors.username = 'Please enter username'
		// } else if (values.username.length > 10) {
		// errors.username = 'username cannot be greater than 10'
		/ /}
		// if (values.password.length < 6) {
		// errors.password = 'Password length cannot be less than 6'
		/ /}
		// return errors
		// },

		validationSchema: Yup.object({
			username: Yup.string().max(10.'Username length cannot be greater than 10').required('Username must be entered'),
			password: Yup.string().min(6.'Password minimum 6 digits').required('Password must be entered')}),// Work with the Yup library for form validation
		onSubmit: handleSubmit
	})
	return (
		// The form item in the form must correspond to the key of the initalValues object by name

		// onBlur indicates that validation begins when the cursor loses focus. Losing focus on a form item with an onBlur event adds a property to formik's Touched attribute to indicate whether the value of the current form item has been changed
		<form onSubmit={formik.handleSubmit}>
			<input
				type="text"
				name="username"
				value={formik.values.username}
				onChange={formik.handleChange}
				onBlur={formik.handleBlur}
			/>
			<p style={{ color: 'red' }}>} {formik.touched. Username && Formik.errors. Username? formik.errors.username : null}</p>
			<input
				type="password"
				name="password"
				value={formik.values.password}
				onChange={formik.handleChange}
				onBlur={formik.handleBlur}
			/>
			<p style={{ color: 'red' }}>
				{formik.touched.password && formik.errors.password ? formik.errors.password : null}
			</p>
			<input type="submit" />
		</form>)}export default App
Copy the code

Build the form as a component

import { Formik, Form, Field, ErrorMessage } from 'formik'
import * as Yup from 'yup'

function App() {
	const initialValues = { username: ' '.password: ' '.select: 'front end' }
	const handleSubmit = values= > {
		console.log(values)
	}

	const schema = Yup.object({
		username: Yup.string().max(10.'User name cannot be greater than 10').required('Username must be entered'),
		password: Yup.string().min(6.'Password must not be less than 6').required('Password must be entered')})return (
		<Formik initialValues={initialValues} onSubmit={handleSubmit} validationSchema={schema}>
			<Form>
				<Field name="username"></Field>
				<ErrorMessage name="username"></ErrorMessage>

				<Field name="password" type="password"></Field>
				<ErrorMessage name="password"></ErrorMessage>{/* input textarea */}<Field name="subject" as="select">
					<option value="Front end">The front end</option>
					<option value="java">java</option>
				</Field>

				<input type="submit" />
			</Form>
		</Formik>)}export default App
Copy the code

Selection criteria for controlled and uncontrolled components

  • Uncontrolled component

    The form data is managed by DOM node, which is characterized by obtaining form data when needed, and the code implementation is relatively simple.

    import { useRef } from 'react'
    
    function App() {
    	const ref = useRef()
    	const handleSubmit = e= > {
    		e.preventDefault()
    		console.log(ref.current.value)
    	}
    	return (
    		<form onSubmit={handleSubmit}>
    			<input type="text" ref={ref} />
    			<input type="submit" />
    		</form>)}export default App
    Copy the code
  • The controlled components

    Form data is managed by state, which is characterized by real-time acquisition of form data and slightly complicated code implementation.

    function App() {
    	const [username, setUsername] = useState(' ')
    	const handleSubmit = e= > {
    		e.preventDefault()
    		console.log(username)
    	}
    	return (
    		<form onSubmit={handleSubmit}>
    			<input type="text" value={username} onChange={e= > setUsername(e.target.value)} />
    			<input type="submit" />
    		</form>)}Copy the code

Choose the standard

Summary: Both controlled and uncontrolled components have their own characteristics and should be selected according to the requirements scenario. In most cases, it is recommended to use controlled components for processing form data, if the form is simple in terms of data interaction, use uncontrolled components, otherwise use controlled components.

scenario uncontrolled controlled
Value when the form is submitted
Verify when the form is submitted
Real-time validation of form item elements
Disable the submit button based on the condition
Enforces the format of the input
Multiple inputs to one data

In other words: if you only do some things when the form is submitted, then you can do both. Controlled can only do some things when the form is submitted, and uncontrolled can do some things when the form is submitted, but controlled can’t.