Unform
Basic form
Basic form
Let's suppose you're creating a sign-in form with two fields, email and
password.
The first step after installing Unform is creating your custom Input component that you will use for every input in your application.
components/Input.js
1import React, { useEffect, useRef } from 'react'2import { useField } from '@unform/core'34export default function Input({ name, ...rest }) {5 const inputRef = useRef(null)6 const { fieldName, defaultValue, registerField, error } = useField(name)78 useEffect(() => {9 registerField({10 name: fieldName,11 ref: inputRef,12 getValue: ref => {13 return ref.current.value14 },15 setValue: (ref, value) => {16 ref.current.value = value17 },18 clearValue: ref => {19 ref.current.value = ''20 },21 })22 }, [fieldName, registerField])2324 return <input ref={inputRef} defaultValue={defaultValue} {...rest} />25}In the above example, we created an input component using the useField hook
exposed by Unform. We also use the useRef hook from React so Unform can access
the input reference directly to get/set the input value.
The next step is creating our form:
SignIn.js
1import React from 'react'2import { Form } from '@unform/web'3import Input from './components/Input'45export default function SignIn() {6 function handleSubmit(data) {7 console.log(data)8 // { email: 'test@example.com', password: '123456' }9 }1011 return (12 <Form onSubmit={handleSubmit}>13 <Input name="email" type="email" />14 <Input name="password" type="password" />1516 <button type="submit">Sign in</button>17 </Form>18 )19}If you're using React Native, proceed to the React Native guide.