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'
3
4export default function Input({ name, ...rest }) {
5 const inputRef = useRef(null)
6 const { fieldName, defaultValue, registerField, error } = useField(name)
7
8 useEffect(() => {
9 registerField({
10 name: fieldName,
11 ref: inputRef,
12 getValue: ref => {
13 return ref.current.value
14 },
15 setValue: (ref, value) => {
16 ref.current.value = value
17 },
18 clearValue: ref => {
19 ref.current.value = ''
20 },
21 })
22 }, [fieldName, registerField])
23
24 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'
4
5export default function SignIn() {
6 function handleSubmit(data) {
7 console.log(data)
8 // { email: 'test@example.com', password: '123456' }
9 }
10
11 return (
12 <Form onSubmit={handleSubmit}>
13 <Input name="email" type="email" />
14 <Input name="password" type="password" />
15
16 <button type="submit">Sign in</button>
17 </Form>
18 )
19}

If you're using React Native, proceed to the React Native guide.

Live example

Edit this page on GitHub

On this page