How To Create Forms in React Native

Forms are an integral part of many applications, both web and mobile. React Native is no exception, and creating forms in React Native is not only very easy, but also very powerful. In this tutorial, we will go over how to create forms in React Native, and how to submit them to a server.

react native forms

What Are Forms and Why Are They Important?

Forms are a way of collecting data from users. Forms can be used to capture user information, such as name, address, email, and more. Forms are also used to submit requests to a server, such as submitting a comment or submitting a payment. Forms are an essential part of many applications, and React Native makes it easy to create them.

Handling Form Inputs in React Native

React Native provides a number of components that make it easy to create forms. The most basic form input is the TextInput component. This component allows users to enter text into a form field. To use this component, you can use the following code:

import { TextInput } from 'react-native';

<TextInput
  placeholder="Enter your name"
  onChangeText={(text) => this.setState({name: text})}
/>

The TextInput component takes a placeholder prop, which is the text that is displayed when the input is empty. It also takes an onChangeText prop, which is a function that is called when the user enters text into the input. In this example, we are setting the name state variable to the text that the user entered.

Validating Forms in React Native

Form validation is an important part of any application. React Native provides a number of tools to help you validate your forms.

The TextInput component takes a validator prop that takes a function that is called when the user enters text into the input. The function should return true if the input is valid, or false if it is not. For example:

import { TextInput } from 'react-native';

<TextInput
  placeholder="Enter your name"
  onChangeText={(text) => this.setState({name: text})}
  validator={(text) => text.length > 0}
/>

In this example, we are validating that the user has entered text that is longer than 0 characters.

React Native also provides the ValidationForm component, which is a wrapper component that can be used to validate a form. The ValidationForm component takes a validate prop which is a function that is called when the form is submitted. The validate function should return an object with a success key set to true if the form is valid, or false if it is not. For example:

import { ValidationForm, TextInput } from 'react-native';

<ValidationForm
  validate={(values) => {
    const errors = {};
    if (!values.name) {
      errors.name = 'Name is required';
    }
    return {
      errors,
      success: Object.keys(errors).length === 0
    };
  }}
>
  <TextInput
    placeholder="Enter your name"
    onChangeText={(text) => this.setState({name: text})}
  />
</ValidationForm>

In this example, we are validating that the name field has been entered. If the name field has not been entered, an error message is set to the errors object.

Submitting Forms in React Native

Once a form has been validated, it can be submitted to a server. React Native provides the FormData component, which is a wrapper component that can be used to submit a form to a server. The FormData component takes a submit prop which is a function that is called when the form is submitted. The submit function should return a Promise that resolves with a response object. For example:

import { FormData, TextInput } from 'react-native';

<FormData
  submit={(values) => {
    return fetch('/submit', {
      method: 'POST',
      body: JSON.stringify(values)
    }).then(response => response.json())
  }}
>
  <TextInput
    placeholder="Enter your name"
    onChangeText={(text) => this.setState({name: text})}
  />
</FormData>

In this example, we are submitting the form data to a /submit endpoint via a POST request.

Complete Form Code Example in React Native

Here is a complete example of a form in React Native, including validation and submission:

import React, { Component } from 'react';
import {
  View,
  Text,
  TextInput,
  ValidationForm,
  FormData
} from 'react-native';

class MyForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      email: ''
    };
  }
  
  render() {
    return (
      <ValidationForm
        validate={(values) => {
          const errors = {};
          if (!values.name) {
            errors.name = 'Name is required';
          }
          if (!values.email) {
            errors.email = 'Email is required';
          }
          return {
            errors,
            success: Object.keys(errors).length === 0
          };
        }}
      >
        <FormData
          submit={(values) => {
            return fetch('/submit', {
              method: 'POST',
              body: JSON.stringify(values)
            }).then(response => response.json())
          }}
        >
          <View>
            <Text>Name:</Text>
            <TextInput
              placeholder="Enter your name"
              onChangeText={(text) => this.setState({name: text})}
            />
            <Text>Email:</Text>
            <TextInput
              placeholder="Enter your email"
              onChangeText={(text) => this.setState({email: text})}
            />
            <Text>Submit</Text>
          </View>
        </FormData>
      </ValidationForm>
    );
  }
}

In this example, we have created a simple form with two inputs: name and email. We have also included validation to make sure the user has entered both fields. Finally, we have included code to submit the form data to a /submit endpoint via a POST request.

Conclusion

Creating forms in React Native is easy and powerful. With the components that React Native provides, you can quickly create forms, validate them, and submit them to a server.