Unform

React Native

React Native

The Unform API is almost identical between web and mobile; below, you can see an Input and a Form using Unform on React Native.

Input component

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

Also, to keep the field uncontrolled, don't store its value within a state, we need to use the references value to hold the field value and use the setNativeProps to set the value native renderer.

Input.js
1import React, { useRef, useEffect, useCallback } from 'react';
2import { Text, TextInput } from 'react-native';
3import { useField } from '@unform/core';
4
5function Input({ name, label, onChangeText, ...rest }) {
6 const inputRef = useRef(null);
7
8 const { fieldName, registerField, defaultValue, error } = useField(name);
9
10 useEffect(() => {
11 inputRef.current.value = defaultValue;
12 }, [defaultValue]);
13
14 useEffect(() => {
15 if (inputRef.current) inputRef.current.value = defaultValue;
16 }, [defaultValue]);
17
18 useEffect(() => {
19 registerField({
20 name: fieldName,
21 ref: inputRef.current,
22 getValue() {
23 if (inputRef.current) return inputRef.current.value;
24
25 return '';
26 },
27 setValue(ref, value) {
28 if (inputRef.current) {
29 inputRef.current.setNativeProps({ text: value });
30 inputRef.current.value = value;
31 }
32 },
33 clearValue() {
34 if (inputRef.current) {
35 inputRef.current.setNativeProps({ text: '' });
36 inputRef.current.value = '';
37 }
38 },
39 });
40 }, [fieldName, registerField]);
41
42 const handleChangeText = useCallback(
43 text => {
44 if (inputRef.current) inputRef.current.value = text;
45
46 if (onChangeText) onChangeText(text);
47 },
48 [onChangeText],
49 );
50
51 return (
52 <>
53 {label && <Text>{label}</Text>}
54
55 <TextInput
56 ref={inputRef}
57 onChangeText={handleChangeText}
58 defaultValue={defaultValue}
59 {...rest}
60 />
61 </>
62 );
63}
64
65export 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.

Edit this page on GitHub