Unform

React Native

The Unform API is almost identic between web and mobile, below you can see an example of an Input and a Form using Unform and React Native.

Input component

In React Native we need to use TextInput provided by the react-native package.

Also, to keep the field uncontrolled, that is, don't store it's value within a state, we need to track input changes and save its value inside the input reference.

Input.js
1import React, {
2 useEffect,
3 useRef,
4 useState,
5} from 'react';
6
7import { TextInput } from 'react-native';
8import { useField } from '@unform/core';
9
10function Input({ name, ...rest }) {
11 const inputRef = useRef(null);
12
13 const { fieldName, registerField, defaultValue, error } = useField(name);
14
15 useEffect(() => {
16 inputRef.current.value = defaultValue;
17 }, [defaultValue]);
18
19 useEffect(() => {
20 registerField({
21 name: fieldName,
22 ref: inputRef.current,
23 path: 'value',
24 clearValue(ref) {
25 ref.value = '';
26 ref.clear();
27 },
28 setValue(ref, value) {
29 ref.setNativeProps({ text: value });
30 inputRef.current.value = value;
31 },
32 getValue(ref) {
33 return ref.value;
34 },
35 });
36 }, [fieldName, registerField]);
37
38 return (
39 <TextInput
40 ref={inputRef}
41 keyboardAppearance="dark"
42 defaultValue={defaultValue}
43 placeholderTextColor="#666360"
44 onChangeText={value => {
45 if (inputRef.current) {
46 inputRef.current.value = value;
47 }
48 }}
49 {...rest}
50 />
51 );
52};
53
54export default Input;

Form component

The only difference between the web form is that in React Native we don't have <button type="submit" />, so the form submit must be triggered manually.

SignIn.js
1import React, { useRef } from 'react';
2import { Button } from 'react-native';
3import { Form } from '@unform/mobile';
4import Input from './components/Input';
5
6export default function SignIn() {
7 const formRef = useRef(null);
8
9 function handleSubmit(data) {
10 console.log(data);
11 // { email: 'test@example.com', password: '123456' }
12 }
13
14 return (
15 <Form ref={formRef} onSubmit={handleSubmit}>
16 <Input name="email" type="email" />
17 <Input name="password" type="password" />
18
19 <Button title="Sign in" onPress={() => formRef.current.submitForm()} />
20 </Form>
21 );
22}

Unform exposes a submitForm function within form reference, so calling it will trigger onSubmit prop passing all the field data to it.

Edit this page on GitHub