Build better forms with React Native UI components
Tags: reactnative, javascript, mobile
Published: 2020-01-06 19:36:58

---
title: Build better forms with React Native UI components
published: true
date: 2019-12-28 17:00:56 UTC
tags: reactnative,javascript,mobile 
canonical_url: https://blog.logrocket.com/build-better-forms-with-react-native-ui-components/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/74iyiqqbdddew8uvsldf.png
---
**Written by [Peter Ekene Eze](https://blog.logrocket.com/author/peterekeneeze/)**✏️

Forms are a very interactive part of our website/product UI. Feedback, surveys, data collection, etc, are some critical aspects of your product that require extensive use of forms. If you don’t get it right, you might be unknowingly giving your users a bad experience which can lead to a drastic reduction in the use of your product.

In this post, we will demonstrate how to build different performant React Native forms with native React Native UI components.

## Prerequisites

- Prior knowledge of React Native will be helpful but not mandatory
- You should have [Xcode](https://developer.apple.com/xcode/) or [Android Studio](https://developer.android.com/studio) installed to run the simulator/emulator
- You should have [Node 10+](https://nodejs.org/en/download/current/) installed

> It is worthy to note that we will not be covering the styling for the app examples we’ll build in this project. This will allow us to focus on functionality. However, all the styles will be available in the [project repository](https://github.com/kenny-io/React-Native-UI-components) for your use.

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

## Getting started

We are going to start with a few installations for those using React Native for the first time. If this is your first time with React Native, be sure to install the required packages and follow these steps accordingly:

**Install the React Native CLI tool using npm like so:**

```jsx
npm install -g react-native-cli
```

Afterward, go ahead and run these React Native commands to create and start a new project.

**Create the animations project and start the server:**

```jsx
react-native init pickerSample

cd pickerSample && npx react-native run-ios // Start the iOS simulator
// OR
cd pickerSample && npx react-native run-android // Android the android emulator
```

If you have [Xcode](https://developer.apple.com/xcode/) or [Android Studio](https://developer.android.com/studio) installed then the commands above will run the project and you should have the simulator show up on the screen like this:

![react native welcome page](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2019/12/welcometorn.png?resize=730%2C1184&ssl=1)

> In my case, I’m using Xcode.

## React Native forms – [picker](https://facebook.github.io/react-native/docs/picker)

The React Native picker component is the equivalent of a dropdown in regular JavaScript. It is basically used to render a list of multiple choices where users then select only one option from the list. The functionality comes in handy when you have to ask a question with varying answers.

Say, for instance, in payment you want to ask a user to select in which currency they want to pay you, it makes sense to render as many currencies as possible depending on the scope of your user base. Let’s see how we can achieve that using the React Native picker component!

In the root directory of the sample project we created, create a new `src/components/Picker.js` file and define some form fields for demonstration purposes:

```jsx
import React, {useState} from 'react';
import {Picker, Text, StyleSheet, View, TextInput, Button} from 'react-native';

const App = () => {
  const [currency, setCurrency] = useState('US Dollar');
  return (
    <View >
      <Text > Demo Form </Text>
      <View>
        <TextInput 
          placeholder="Email" />
        <TextInput
          secureTextEntry={true}
          placeholder="Password"
        />
        <Picker
          selectedValue={currency}
          onValueChange={currentCurrency => setCurrency(currentCurrency)}>
          <Picker.Item label="USD" value="US Dollars" />
          <Picker.Item label="EUR" value="Euro" />
          <Picker.Item label="NGN" value="Naira" />
        </Picker>
        <Text>
          Selected: {currency}
        </Text>
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  //Check project repo for styles
});

export default App;
```

To output this component, we need to update our App.js file like so:

```jsx
import React from 'react';
import Picker from './src/components/Picker'
const App = () => {
  return (
    <Picker />
  );
};
export default App;
```

What we’ve done is simply render the Picker component we created in the `src/components/Picker.js` file here. When the app loads, the picker file is rendered. If we run the app at this point, we should get the following output on the simulator:

![picker file](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2019/12/pickerfile.gif?resize=730%2C1245&ssl=1)

You can take your knowledge of this component further by learning what props the components take in to control how the picker options are displayed. A good resource for this will be the [official documentation](https://facebook.github.io/react-native/docs/picker#props) for the picker component.

## React Native forms – [slider](https://github.com/react-native-community/react-native-slider)

The React Native slider component is mostly used to select a single value from a range of values. This feature is especially in forms when you need to present users with a range of values from a defined `minimumValue` to a `maximumValue`.

A practical application example of this component will be in product or performance ratings. To demonstrate this, we’ll create a new component, build out our form, and implement the slider.

In the `src` we created earlier, create a new `src/components/Slider.js` file and update it with the code below:

```jsx
import React, {useState} from 'react';
import {Slider, Text, StyleSheet, View, TextInput} from 'react-native';

const App = () => {
  const [value, setValue] = useState(0);
  return (
    <View>
      <Text> Demo Form </Text>
      <View>
        <TextInput placeholder="Email" />
        <TextInput
          secureTextEntry={true}
          placeholder="Password"
        />
        <Text>
          Rate your teams performance this quarter
        </Text>
        <Slider
          step={1}
          minimumValue={0}
          maximumValue={100}
          value={value}
          onValueChange={slideValue => setValue(slideValue)}
          minimumTrackTintColor="#1fb28a"
          maximumTrackTintColor="#d3d3d3"
          thumbTintColor="#b9e4c9"
        />
        <Text>
          Slide value: {value}%
        </Text>
      </View>
    </View>
  );
};

export default App;
```

Here, we import the slider component from React Native core. It will be worthy to note that the slider component has been extracted from React Native core and will be removed in future releases. When that happens, the slider component will be installed directly from:

```jsx
npm i @react-native-community/slider --save
```

And then imported from:

```jsx
import Slider from '@react-native-community/slider';
```

This procedure works but still requires some rather manual processes that are not well documented yet. Which is why we’ll go ahead with the conventional import from React Native core in this demonstration.

To render this component when the app runs and see what it looks like, we’ll update the `App.js` file again like so:

```jsx
import React from 'react';
import Picker from './src/components/Picker'
import Slider from './src/components/Slider'
const App = () => {
  return (
    <Slider />
  );
};
export default App;
```

### Slider demo

Run the app again, and we should get the following output:

![slider](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2019/12/slider.gif?resize=730%2C1242&ssl=1)

### More application examples

This component has a wide range of applications that goes beyond forms. Here’s a screenshot from the Gmail iOS app sync settings:

![sync settings](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2019/12/syncsettings.jpg?resize=730%2C554&ssl=1)

## React Native forms – [modal](https://facebook.github.io/react-native/docs/modal)

The modal UI component allows you to present content directly on top of a parent (enclosing) view. This functionality is usually very useful when you have the need to perform a number of activities while avoiding navigation into different pages.

Just like the slider component, the React Native [modal component](https://facebook.github.io/react-native/docs/modal) has also been extracted from React Native core into the [community package](https://github.com/react-native-community/react-native-modal) that is now available via npm. The major difference is the added features that came with the `react-native-modal` package. Examples are animations, inline style prop, more customization options, etc. As a result, the earlier modal component from React Native core will be deprecated in future releases.

### Modal demo

To further exemplify it, we’ll build a demo app to show how you can implement the modal component on your own. In my case, I want to show a login form in my modal when a user clicks it but first, let’s install the package from npm:

```jsx
npm i react-native-modal
#OR
yarn add react-native-modal
```

Then we create a `Login.js` file in the `/components` directory. In this file, we’ll define the form we want to render on the modal:

```jsx
import React, {useState} from 'react';
import { Text, View, TextInput} from 'react-native';

const LoginForm = () => {
  const [value, setValue] = useState(0);
  return (
    <View>
      <Text> Login Form </Text>
      <View>
        <TextInput placeholder="Enter Email" />
        <TextInput
          secureTextEntry={true}
          placeholder="Enter Password"
        />
      </View>
    </View>
  );
};

export default LoginForm;
```

This is a login form that practically does nothing. I’m only defining the `email` and `password` fields to give you a visual understanding of the supposed use case. Next, we’ll create the modal component `src/components/Modal.js` and update it like so:

```jsx
import React, { useState} from 'react';
import {Button, View, StyleSheet} from 'react-native';
import Modal from 'react-native-modal';
import LoginForm from './Login';

const ModalDemo = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const toggleModal = () => {
    setIsModalVisible(!isModalVisible);
  };
  return (
    <View style={styles.container}>
      <Button title="Click here to login" onPress={toggleModal} />
      <Modal
        isVisible={isModalVisible}>
        <View>
          <LoginForm />
          <View>
            <Button title="Hide modal" onPress={toggleModal} />
          </View>
        </View>
      </Modal>
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#E6E6FA',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
export default ModalDemo;
```

Here, we first import the React Native modal component we installed earlier. We also did the same for the login form we created to render on the modal.

Next, we render the modal with buttons to show and hide the modal. Initially, the modal will be hidden. We’ll do this by setting the `isVisible` prop of the modal component to false. When the login button is clicked, we call the `toggleModal()` function that changes the value of the `isVisible` prop from false to true. When that happens, the modal will then be visible.

In the modal component, we rendered the login form and also a button to hide the modal by toggling the value of the `isVisible` prop.

![modal](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2019/12/modal.gif?resize=730%2C1264&ssl=1)

There are a number of other props that are available to the modal component for other customizations like styling and animations.

For instance, we can decide to alter the default behavior of the modal by modifying the animation styles. E.g, let’s slow down the modal exit speed when we click the hide modal button. We can do this with the `animationOutTiming` prop by setting a higher value to it. The same applies to animating the modal out from the top of the screen rather than below as we’ve seen in the last recording above.

### More animation props

```jsx
return (
  <View style={styles.container}>
    <Button title="Click here to login" onPress={toggleModal} />
    <Modal
      animationOutTiming={1000}
      animationOut={'slideOutUp'}
      isVisible={isModalVisible}>
      <View>
        <LoginForm />
        <View style={{marginTop: 150}}>
          <Button title="Hide modal" onPress={toggleModal} />
        </View>
      </View>
    </Modal>
  </View>
);
```

And this update will yield a different modal behavior as you’d expect.

![modal 2](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2019/12/modal2.gif?resize=730%2C1253&ssl=1)

You can find more available props for the modal component [here](https://github.com/react-native-community/react-native-modal).

## Conclusion

Here, we have explained and demonstrated how to build better React Native forms using only native UI components. We covered the picker component, the slider, and also the modal. We built some really nice examples to give you a hands-on experience of how the components work and how to build yours. You can find the source code for this project [here](https://github.com/kenny-io/React-Native-UI-components).

* * * 
## Plug: [LogRocket](https://logrocket.com/signup/), a DVR for web apps
 
![LogRocket Dashboard Free Trial Banner](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png?resize=1200%2C677&ssl=1)
 
[LogRocket](https://logrocket.com/signup/) is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
 
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.
 
[Try it for free](https://logrocket.com/signup/).
* * *

The post [Build better forms with React Native UI components](https://blog.logrocket.com/build-better-forms-with-react-native-ui-components/) appeared first on [LogRocket Blog](https://blog.logrocket.com).