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';45function Input({ name, label, onChangeText, ...rest }) {6 const inputRef = useRef(null);78 const { fieldName, registerField, defaultValue, error } = useField(name);910 useEffect(() => {11 inputRef.current.value = defaultValue;12 }, [defaultValue]);1314 useEffect(() => {15 if (inputRef.current) inputRef.current.value = defaultValue;16 }, [defaultValue]);1718 useEffect(() => {19 registerField({20 name: fieldName,21 ref: inputRef.current,22 getValue() {23 if (inputRef.current) return inputRef.current.value;2425 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]);4142 const handleChangeText = useCallback(43 text => {44 if (inputRef.current) inputRef.current.value = text;4546 if (onChangeText) onChangeText(text);47 },48 [onChangeText],49 );5051 return (52 <>53 {label && <Text>{label}</Text>}5455 <TextInput56 ref={inputRef}57 onChangeText={handleChangeText}58 defaultValue={defaultValue}59 {...rest}60 />61 </>62 );63}6465export 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';56export default function SignIn() {7 const formRef = useRef(null);89 function handleSubmit(data) {10 console.log(data);11 // { email: 'test@example.com', password: '123456' }12 }1314 return (15 <Form ref={formRef} onSubmit={handleSubmit}>16 <Input name="email" type="email" />17 <Input name="password" type="password" />1819 <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.