Build forms in React Native with tcomb-form-native
Tags: forms, mobileappdevelopment, javascript, react
Published: 2020-07-25 11:06:41

---
title: Build forms in React Native with tcomb-form-native
published: true
date: 2020-02-25 13:40:02 UTC
tags: forms,mobileappdevelopment,javascript,react
canonical_url: https://medium.com/@ows_ali/build-forms-in-react-native-with-tcomb-form-native-cd10f9435fcc
---

Building forms from scratch is hectic than we may imagine. tcomb-form-native is one powerful library, that helps building complex input forms having validation, maintain state on input or submit, or initializing the form with default values, styling the input fields etc. Here is the official link as well:

[gcanti/tcomb-form-native](https://github.com/gcanti/tcomb-form-native)

In this tutorial, we will explore the library while writing example codes to see how it practically works.

Let’s get started with obvious steps:

Initializing new RN project:

```
react-native init tcombFormNativeTutorial
```

Installing tcomb library:

```
npm i --save tcomb-form-native
```

**Building first form:**

Lets build a new component in Tcomb.js which renders our form. tcomb automatically generates a form based on provided domain model, ‘PersonModel’ in our case, as follows:

```
import React, { Component } from 'react';
import { View } from 'react-native';
import t from 'tcomb-form-native'

let Form = t.form.Form
class Tcomb extends Component {
  constructor(props){
    super(props)
  }
  render() {
    let PersonModel = t.struct({
      name: t.String, // a required string
      surname: t.maybe(t.String), // an optional string
      age: t.Number, // a required number
      rememberMe: t.Boolean, // a boolean
    });
    return (
      <View>
       <Form
         ref='form'
         type={PersonModel}
         // options={{}}
         // value={{}}
         // onChange={{}}
       />
      </View>
    )
  }
}
export default Tcomb;
```

![](https://cdn-images-1.medium.com/max/1024/1*Rbwa79HIukI-iA0d8CfvVQ.png)

The above form adds Text Input, Numeric and Boolean input fields. And notice, it adds labels on its own, and it adds mandatory validation by default and you need to use t.maybe() for optional fields (i.e. ‘surname’ in the above form).

**Validating input:**

To verify the fields we call **getValue()** function on form using ref. We will add a submit button and its handler which ultimately triggers the validation of the fields:

```
submitForm() {
  var value = this.refs.personForm.getValue();
  if (value) {
    // if validation fails, value will be null
    ToastAndroid.show('Validation successful', ToastAndroid.SHORT);
  } else {
    ToastAndroid.show('Please fix errors', ToastAndroid.SHORT);
  }
}
```

and in render

```
<TouchableOpacity style={styles.button} onPress={this.submitForm}>
  <Text style={styles.buttonText}>Submit</Text>
</TouchableOpacity>
```

here is the result

![](https://cdn-images-1.medium.com/max/1024/1*ifSu_J39f_NcLumATvqEcg.png)

#### Adding default values:

Let’s add default values to our form. We add this.state.value in our constructor

```
this.state = {
  value: {
    name: 'First',
    surname: 'Last',
    age: 25,
    rememberMe: true,
  },
};
```

and update form as follows

```
<Form
  ref='personForm'
  type={PersonModel}
  // options={{}}
  value={this.state.value}
  // onChange={{}}
/>
```

**Changing labels**

To change the label from ‘Name’ to ‘First Name’, we add options inside render:

```
let options = {
  fields: {
    name: {
      label: 'First Name',
    },
  },
};
```

and update our form

```
<Form
  ref='personForm'
  type={PersonModel}
  options={options}
  value={this.state.value}
  // onChange={{}}
/>
```

**Hint/Help Text:**

```
let options = {
  fields: {
    name: {
      label: 'First Name',
      help: 'Must be less than 20 characters',
    },
  },
};
```

![](https://cdn-images-1.medium.com/max/1024/1*VQwkGO21X7pz-BRUIhW_LQ.png)

#### Dropdown field:

Let us add a dropdown field of gender:

```
let PersonModel = t.struct({
  name: t.String, // a required string
  surname: t.maybe(t.String), // an optional string
  age: t.Number, // a required number
  rememberMe: t.Boolean, // a boolean
  gender: t.enums({M: 'Male', F: 'Female'}, 'gender'),
});
```

![](https://cdn-images-1.medium.com/max/1024/1*3vWRI8L_XSMoPoOHH_mCYA.png)

**Disabling fields:**

Here we disable the fields ‘age’, ‘rememberMe’ and ‘gender’. Notice, we sometimes use ‘editabale’ and sometimes ‘disabled’ configuration variables

```
let options = {
  fields: {
    name: {
      label: 'First Name',
    },
    age: {
      editable: false,
    },
    rememberMe: {
      editable: false,
    },
  },
};
```

![](https://cdn-images-1.medium.com/max/1024/1*gfHLmdYarhykVCj7WxykrA.png)

#### **Conclusion:**

We built a simple form using tcomb-form-native library. We used textinput, dropdown, toggle switch, we also added mandatory validation and added a form submission handler. There will be another tutorial in the continuation where I will show how can you add custom advanced validation to the fields. This project is also uploaded on Github for reference:

[https://github.com/ows-ali/tcombFormNativeTutorial](https://github.com/ows-ali/tcombFormNativeTutorial)