Kako zgraditi obrazce v reakciji s knjižnico odvečne kljuke

V tem članku bomo raziskali knjižnico odzivnih oblik.

Naučili se boste, kako uporabljati in integrirati to knjižnico z Reactom. Videli bomo tudi, zakaj postaja priljubljena izbira za izdelavo preprostih in zapletenih obrazcev z dodano podporo za obdelavo zapletenih preverjanj.

Začnimo

Delo z obrazci v Reactu je zapletena naloga. In postane še bolj zapleteno, ko se število vnosnih polj poveča skupaj z validacijami.

Oglejte si spodnjo kodo:

 import React, { useState } from "react"; import "./styles.css"; export default function App() { const [state, setState] = useState({ email: "", password: "" }); const handleInputChange = (event) => { setState((prevProps) => ({ ...prevProps, [event.target.name]: event.target.value })); }; const handleSubmit = (event) => { event.preventDefault(); console.log(state); }; return ( Email Password Login ); }

Tukaj je predstavitev Code Sandbox: //codesandbox.io/s/login-form-zjxs9.

V zgornji kodi imamo samo 2 vnosni polji, in sicer emailin password, in gumb za oddajo.

Vsakemu vnosnemu polju je dodan valuein onChangevodnik, tako da lahko stanje posodobimo na podlagi uporabnikovega vnosa.

Dodali smo tudi handleSubmitmetodo, ki v konzolo prikaže podatke, vnesene v obrazec.

To izgleda v redu. Kaj pa, če moramo dodati preverjanja veljavnosti, kot so zahtevano preverjanje polj, preverjanje minimalne dolžine, preverjanje gesla, preverjanje veljavnosti e-poštnega polja in prikaz ustreznih sporočil o napakah?

Koda bo s povečevanjem števila vnosnih polj in njihovih preverjanj postala bolj zapletena in daljša.

To je zelo pogosta zahteva v kateri koli aplikaciji. Torej, da enostavno delo z obrazci, obstajajo različne knjižnice so na voljo, kot so Formik, redux-form, react-final-form, react-hook-formin tako naprej.

Toda tisto, ki dobiva veliko popularnost, je react-hook-formknjižnica.

Zdaj pa se naučimo, zakaj in kako jo uporabljati. Za to bomo ustvarili novo aplikacijo React.

Ustvarite nov projekt React z zagonom naslednjega ukaza s terminala:

npx create-react-app react-hook-form-demo

Ko je projekt ustvarjen, izbrišite vse datoteke iz srcmape in ustvarite nove index.jsin styles.cssdatoteke znotraj srcmape.

Če želite namestiti knjižnico obrazcev, v terminalu izvedite naslednji ukaz:

yarn add react-hook-form

Kako ustvariti začetne strani

Odprite src/index.jsdatoteko in vanjo dodajte naslednjo vsebino:

 import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(, document.getElementById('root'));

Odprite src/styles.cssdatoteko in dodajte vsebino od tukaj.

Zdaj App.jsv srcmapi ustvarite novo datoteko z naslednjo vsebino:

 import React from "react"; import "./styles.css"; export default function App() { return ( Email Password Login ); }

Tukaj smo obrazcu pravkar dodali polji e-pošte in gesla.

Ustvarjanje osnovnega obrazca z uporabo reakcijske kljuke

react-hook-formKnjižnica zagotavlja useFormkavelj, ki ga lahko uporabljamo za delo z obrazci.

useFormKavelj uvozite tako:

import { useForm } from 'react-hook-form';

Uporabite useFormkavelj tako:

const { register, handleSubmit, errors } = useForm();

Tukaj,

  • register je funkcija, ki se uporablja kot referenca, ki jo zagotavlja useFormkavelj. Dodelimo ga lahko vsakemu vnosnemu polju, tako da react-hook-formlahko sledimo spremembam vrednosti vhodnega polja.
  • handleSubmit je funkcija, ki jo lahko pokličemo ob oddaji obrazca
  • Napake bodo vsebovale napake pri preverjanju, če obstajajo

Zdaj vsebino App.jsdatoteke nadomestite z naslednjo vsebino:

 import React from "react"; import { useForm } from "react-hook-form"; import "./styles.css"; export default function App() { const { register, handleSubmit, errors } = useForm(); const onSubmit = (data) => { console.log(data); }; return ( Email Password Login ); }

V zgornji kodi smo podali referenco za vsako vnosno polje, ki smo ga dobili s useFormkavlja.

ref={register}

Dodali smo tudi funkcijo onSubmit, ki je posredovana funkciji handleSubmit.

Upoštevajte, da smo za vsako vnosno polje dali enolično ime, ki je obvezno, da react-hook-formlahko sledimo spreminjajočim se podatkom.

Ko pošljemo obrazec, bo funkcija handleSubmit obravnavala oddajo obrazca. Uporabniku vnesene podatke bo poslal v funkcijo onSubmit, ki jo beležimo v konzolo.

const onSubmit = (data) => { console.log(data); };

Zdaj zaženite aplikacijo z zagonom yarn startukaza.

Kot lahko vidite, se ob oddaji obrazca v konzoli prikažejo podrobnosti, ki jih vnese uporabnik.

V primerjavi s kodo brez react-hook-form(ki smo jo videli na začetku tega članka) je ta koda veliko preprostejša. To je zato, ker nam ni treba dodati obdelovalca valuein onChangeza vsako vnosno polje in ni treba sami upravljati stanja aplikacije.

Kako dodati validacije obrazcu

Now, let’s add the required field and minimum length validation to the input fields.

To add validation we can pass it to the register function which is passed as a ref to each input field like this:

We also want to display the error message if the validation fails.

When the validation fails, the errors object coming from useForm will be populated with the fields for which the validation failed.

Open the App.js file and replace its contents with the following content:

 import React from "react"; import { useForm } from "react-hook-form"; import "./styles.css"; export default function App() { const { register, handleSubmit, errors } = useForm(); const onSubmit = (data) => { console.log(data); }; return ( Email  {errors.email && errors.email.type === "required" && ( 

Email is required.

)} {errors.email && errors.email.type === "pattern" && (

Email is not valid.

)} Password {errors.password && errors.password.type === "required" && (

Password is required.

)} {errors.password && errors.password.type === "minLength" && (

Password should be at-least 6 characters.

)} Login ); }

Here, for the email input field, we have provided the required and pattern matching validations.

So as you type in the email input field, the validation will run once the form is submitted.

If the validation failed, then the errors.email field inside the errors object will be populated with the type field which we used to display the error message.

 {errors.email && errors.email.type === "required" && ( 

Email is required.

)}

In the similar way, we have added the password field validation.

So as you can see, each input field is automatically focused if there is any validation error for the that input field when we submit the form.

Also, the form is not submitted as long as there is a validation error. You can see that the console.log statement is only printed if the form is valid.

So using react-hook-form reduced the amount of code that we have to write. The validation is also responsive, so once the field becomes valid, the error message goes away instantly.

But as the number of validations for each field increases, the conditional checks and error message code will still increase. So we can further refactor the code to make it even simpler.

Take a look at the below code:

 import React from 'react'; import { useForm } from 'react-hook-form'; import './styles.css'; export default function App() { const { register, handleSubmit, errors } = useForm(); const onSubmit = (data) => { console.log(data); }; return ( Email  {errors.email && 

{errors.email.message}

} Password {errors.password && (

{errors.password.message}

)} Login ); }

In the code above, we have changed the email and password validation code.  

For the email input field, we changed this previous code:

to the below new code:

Here, we’ve directly provided the error message we want to display while adding the validation itself.

So we no longer need to add extra checks for each validation. We are displaying the error message using the message property available inside the errors object for each input field.

{errors.email && 

{errors.email.message}

}

So by doing it this way, the code is further simplified which makes it easy to add extra validations in future.

Note that if there are validation errors, the onSubmit handler will not be executed and the corresponding input field will automatically be focused (which is a good thing).

How to Add a Custom Validation Method

You can even provide a custom validation for the input field by adding a validate method. This is useful if you need to perform complex validations like this:

// validation function const validatePassword = (value) => { if (value.length < 6) { return 'Password should be at-least 6 characters.'; } else if ( !/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s)(?=.*[[email protected]#$*])/.test(value) ) { return 'Password should contain at least one uppercase letter, lowercase letter, digit, and special symbol.'; } return true; }; // JSX 

Now you know how to use react-hook-form to create forms in React along with complex validations.

Why react-hook-form is better than the alternatives

Let’s look at some additional reasons that react-hook-form should become your preferred choice for working with forms.

  • Code complexity is less as compared to formik, redux-form and other alternatives.
  • react-hook-form integrates well with the yup library for schema validation so you can combine your own validation schemas.
  • The number of re-renders in the application is small compared to the alternatives.
  • Mounting time is less as compared to the alternatives.

For the actual comparison metrics, read more here.

Conclusion

V tem članku smo videli, kako uporabljati react-hook-formin zakaj je veliko razvijalcev najprimernejša izbira za izdelavo tako preprostih kot zapletenih oblik v Reactu.

Izvorno kodo GitHub za to aplikacijo najdete tukaj.

Če vam je bil ta članek všeč, vam bodo všeč tudi moji drugi članki.

Naročite se na moje tedensko glasilo in se pridružite drugim 1000+ naročnikom, da boste neposredno v mapo »Prejeto« prejemali neverjetne nasvete, trike in članke.