Forms in React Native, The right way

Youssouf EL Azizi
March 18th, 2020 · 4 min read

Handling forms in react native is a crucial task in your journey as a react native developer, you can’t think about developing a new react native app without dealing with forms, at least for login and sign up screen in case your app is retrieving data in the most of the cases. Finding a solution for such a repetitive task will help you save a lot of time for your next sprint 😉.

Through My 2 years experience As a react native developer, I used to use different approaches to handle forms without feeling confident about the best solution that deserves a new article. Today I am confident to share with you the right way to handle forms in your next react native project. I would be more than happy to hear your remarks and thoughts about this solution ( this is why i am sharing this article)

This article is a step-by-step tutorial to create a generic form component that can be used whenever you need to deal with forms.

if you are impatient and want to go straight to the code, you can play around with the solution in this Snack Editor Project. 😀

Approach

The idea is based on empowering react-hook-form with a smart form component that can compose any Input child, collect data and handle errors automatically. Also, we are going to provide an automatic way to autofocus the next input after pressing the next keyboard button and adding a keyboard aware capabilty for our inputs.

To make it clear we need first to create a custom Input component with error handling. then create a smart Form Component that injects all react-hook-form properties correctly for each component, and finally implement the autofocus and keyboard aware features.

This is the end result of our Work.

You can’t record keyboard for secureTextEntry={true} Input, that’s why you are seeing my password 😀


Befor starting I think you are wondering 👇

Why React-hooks-form

Form React-hook-form official documentation, one of the primary goals of React Hook Form is to reduce the amount of code that you have to write. As you can see from our final result, React hooks form is really easy to use and it takes a small amount of code. More than that if we can compare react-hook-form to the most used solution to handle forms in React such as Formik and redux-form, it seems clear that react-hook-form will be the winner regarding bundle size and performance.

React-hook-form home page contains a complete section illustrating why you should use it over other libraries.

Let’s get started

Create a Custom Input

In the first step, we are going to create a custom text input component with error handling, As you see we try to make the component as simple as possible but you could style your component as you want or even use a TextInput from built-in UI library such us react-paper or native-base, the solution will work as expected regardless of your Input implementation as long as the custom input implements the React forward API and has a required name property.

1import * as React from 'react'
2import {
3 View,
4 TextInput,
5 Text,
6 StyleSheet,
7 ViewStyle,
8 TextStyle,
9 TextInputProps,
10} from 'react-native'
11import { FieldError } from 'react-hook-form'
12interface Props extends TextInputProps {
13 name: string
14 label?: string
15 labelStyle?: TextStyle
16 error?: FieldError | undefined
17}
18
19export default React.forwardRef<any, Props>(
20 (props, ref): React.ReactElement => {
21 const { label, labelStyle, error, ...inputProps } = props
22
23 return (
24 <View style={styles.container}>
25 {label && <Text style={[styles.label, labelStyle]}>{label}</Text>}
26 <TextInput
27 autoCapitalize="none"
28 ref={ref}
29 style={[
30 styles.inputContainer,
31 { borderColor: error ? '#fc6d47' : '#c0cbd3' },
32 ]}
33 {...inputProps}
34 />
35 <Text style={styles.textError}>{error && error.message}</Text>
36 </View>
37 )
38 }
39)

You can use The InputProps type from our component to implement your custom one and to make sure your component is ready for the next step.

Create Form Component

The idea behind the form component is to iterate component children and register all input by adding the correct properties. The form component will receive its prop from the useForm hook and these are properties that we need to be passed to Make sure our Form Component works correctly.

  • register: This method allows us to register the input Ref with a unique name and validation rules into React Hook Form.
1register: ({name}: {name: string}, validation: ValidationOptions) => void;
  • setValue: This function will help us to dynamically set input value to the correct ref using name property. We need to use setValue because we are going to use a custom register call.
1setValue: (name: string, value: string, shouldValidate?: boolean) => void;
  • Errors: Object containing form errors and error messages corresponding to each input.
  • Validation: Object containing form validation rules for each input.

If you are not familiar with react-hook-form, check the docs here

In order to inject Props to Input children we are going to use React.createElement API to create new Element for every child with a name property.

By using the name property We can filter all Input that needs to be part of our form data or return the child without creating a new one if it’s not the case.

For each Input child we use the register function to register inputs ref manually and inject validation rules.

By using the custom register call , we will need to update the input value manually with setValue using the onChangeText Input property.

Finally we’ll add the error and error message corresponding to each input.

1export default ({
2 register,
3 errors,
4 setValue,
5 validation,
6 children,
7}: Props) => {
8 return (
9 <>
10 {(Array.isArray(children) ? [...children] : [children]).map(child => {
11 return child.props.name
12 ? React.createElement(child.type, {
13 ...{
14 ...child.props,
15 ref: () => {
16 register(
17 { name: child.props.name },
18 validation[child.props.name]
19 )
20 },
21 onChangeText: (v: string) =>
22 setValue(child.props.name, v, true),
23 key: child.props.name,
24 error: errors[child.props.name],
25 },
26 })
27 : child
28 })}
29 </>
30 )
31}

Now, Our Form Component is Ready, but before closing the article I want to improve The form component by providing a way to autofucuse the next input automatically after pressing next keyboard button, wich I think is an important feature to ensure good user experience.

The only way to focus input in react-native is to have a ref for your input instance and call the focus method whenever you want the input to be focused.

To make this work we need to have access to all Inputs refs, detect the next input and call the focus method.

We can make this possible by using an Inputs React Ref in our Form component,then we push children Input Refs one by one.

To focus the next Input, we need to implemnet the onSubmitEditing property wihch will be called after pressing the next keyboad button. we need to focus the next input by invoking focus methode for the next input Ref or call blur if the next input Ref doesn’t exist..

Worth mentioning, that onSubmitEditing callback is called after blur event. So the keyboard may go crazy if it focuses on the next element immediately.It might be helpful to set blurOnSubmit={false} to all elements in the form.

1import * as React from 'react';
2import {TextInput} from 'react-native';
3import {ValidationOptions, FieldError} from 'react-hook-form';
4
5interface ValidationMap {
6 [key: string]: ValidationOptions;
7}
8
9interface ErrorMap {
10 [key: string]: FieldError | undefined;
11}
12
13interface Props {
14 children: JSX.Element | JSX.Element[];
15 register: ({name}: {name: string}, validation: ValidationOptions) => void;
16 errors: ErrorMap;
17 validation: ValidationMap;
18 setValue: (name: string, value: string, validate?: boolean) => void;
19}
20
21export default ({
22 register,
23 errors,
24 setValue,
25 validation,
26 children,
27}: Props) => {
28 const Inputs = React.useRef < Array < TextInput >> []
29
30 return (
31 <>
32 {(Array.isArray(children) ? [...children] : [children]).map(
33 (child, i) => {
34 return child.props.name
35 ? React.createElement(child.type, {
36 ...{
37 ...child.props,
38 ref: (e: TextInput) => {
39 register(
40 { name: child.props.name },
41 validation[child.props.name]
42 )
43 Inputs.current[i] = e
44 },
45 onChangeText: (v: string) =>
46 setValue(child.props.name, v, true),
47 onSubmitEditing: () => {
48 Inputs.current[i + 1]
49 ? Inputs.current[i + 1].focus()
50 : Inputs.current[i].blur()
51 },
52 blurOnSubmit: false,
53 key: child.props.name,
54 error: errors[child.props.name],
55 },
56 })
57 : child
58 }
59 )}
60 </>
61 )
62}

Our Last step is To Use react-native-keyboard-aware-scroll-view component that handles keyboard appearance and automatically scrolls to focused TextInput.

Yep! Our Form Component is Ready for Production 😎And you can play around with it in thisSnack Editor Project.

1//App.tsx
2
3type FormData = {
4 name: string
5 email: string
6 password: string
7}
8
9export default () => {
10 const { handleSubmit, register, setValue, errors } = useForm<FormData>()
11
12 const onSubmit = (data: FormData) => {
13 Alert.alert('data', JSON.stringify(data))
14 }
15
16 return (
17 <KeyboardAwareScrollView contentContainerStyle={styles.container}>
18 <Hero />
19 <View style={styles.formContainer}>
20 <Form {...{ register, setValue, validation, errors }}>
21 <Input name="name" label="Name " />
22 <Input name="email" label="Email" />
23 <Input name="password" label="Password" secureTextEntry={true} />
24 <Button title="Submit" onPress={handleSubmit(onSubmit)} />
25 </Form>
26 </View>
27 </KeyboardAwareScrollView>
28 )
29}

I hope you found that interesting, informative, and entertaining. I would be more than happy to hear your remarks and thoughts about this solution in The comments.

If you think other people should read this post. Tweet,share and Follow me on twitter for the next articles.

More articles from Obytes

Avoid Cloudflare bypassing by using secret headers.

How-to avoid bypassing Cloudflare protection by using Cloudflare Workers to add a secret header.

March 10th, 2020 · 2 min read

Dockerized Developer Environment for Django Applications

Steps to deploy and run the application in a development environment using Docker.

March 9th, 2020 · 3 min read

ABOUT US

Our mission and ambition is to challenge the status quo, by doing things differently we nurture our love for craft and technology allowing us to create the unexpected.