Unform

Basic form

Table of Contents

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 will be used 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.current,
12 path: 'value',
13 });
14 }, [fieldName, registerField]);
15
16 return <input ref={inputRef} defaultValue={defaultValue} {...rest} />;
17}

In the above example, we create 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 React Native guide.

Live example

Edit this page on GitHub