Peter Ekene Eze Learn, Apply, Share

Build better forms with React Native UI components

6 min read 1792

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 or Android Studio installed to run the simulator/emulator
  • You should have Node 10+ 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 for your use.

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:

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:

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 or Android 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

In my case, I’m using Xcode.

React Native forms – 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!

We made a custom demo for .
No really. Click here to check it out.

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:

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:

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

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 for the picker component.

React Native forms – 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:

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:

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

And then imported from:

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:

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

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

React Native forms – 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 has also been extracted from React Native core into the community package 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:

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:

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:

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

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

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

You can find more available props for the modal component here.

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.

 

Peter Ekene Eze Learn, Apply, Share

Leave a Reply