Unform
React Native
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, { useEffect, useRef, useState } from 'react';23import { TextInput } from 'react-native';4import { useField } from '@unform/core';56function Input({ name, ...rest }) {7 const inputRef = useRef(null);89 const { fieldName, registerField, defaultValue, error } = useField(name);1011 useEffect(() => {12 inputRef.current.value = defaultValue;13 }, [defaultValue]);1415 useEffect(() => {16 registerField({17 name: fieldName,18 ref: inputRef.current,19 path: 'value',20 clearValue(ref) {21 ref.value = '';22 ref.clear();23 },24 setValue(ref, value) {25 ref.setNativeProps({ text: value });26 inputRef.current.value = value;27 },28 getValue(ref) {29 return ref.value;30 },31 });32 }, [fieldName, registerField]);3334 return (35 <TextInput36 ref={inputRef}37 keyboardAppearance="dark"38 defaultValue={defaultValue}39 placeholderTextColor="#666360"40 onChangeText={value => {41 if (inputRef.current) {42 inputRef.current.value = value;43 }44 }}45 {...rest}46 />47 );48}4950export 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 to it.