Almost all the applications consist of forms- right from handling the entrance: sign up to the departure: contact us. Forms let you interact with web applications better by giving feedback or by contacting them.

When you are working with React Native forms, you have to manage the state for every input field, you need to make sure that all fields validate the user input, and you have to handle submit form functionality once the form is filled. It might take longer and increase your work if you start from scratch. To make development easier and faster, we can use Redux Form.

If you’ve not worked with the redux form before, don’t worry; here’s a series of tutorials in two parts- in the first part, with the help of an example, we will integrate the redux form with your React Native application. Then, in the second part, we will dig deeper into redux form and implement a login module with the head-to-toe implementation of redux and redux middleware.

Without further ado, let’s get started with the redux form tutorial.

Table of Contents

Goal

Before learning the implementation of the redux form, let’s see the below video so that you can have a better understanding of what we will be developing further.

Introducing Redux Form

First of all,let’s start understanding it with What is redux form?

The React redux-form is an efficient way to manage forms, powered by Redux. It is a Higher Order Component which, under the hood, uses react-redux for managing HTML forms in React and for ensuring that it uses Redux for storing data. The redux-form consists of these components for developing an application:

Redux Reducer: It manages and maintains a redux-form state by listening to the dispatched actions.

React Component Decorator: It encloses the entire form in HOC and provides functionality through props.

Field Component: It connects individual input fields to the Redux store.

Action Creators: It interacts with the forms throughout your app.

In this Redux Form tutorial, I’ve covered below functionalities from redux-form:

  • Field
  • Field-Level Validation
  • handleSubmit
  • Resetting form
  • formValueSelector

Steps to Implement Redux Form in React Native App

Implement Redux Form in React Native App

Enough of the theory part; now it’s time to build our demo application. Let’s get our hands-on coding to implement React Native form with redux-form. Follow these steps to implement the redux form in React Native app.

Installation & Setup

Add the redux-form package to your project

Copy Text
$ yarn add redux-form
# or, using npm:
$ npm install redux-form

Now first, we have to import the reducer from the redux-form package to our application’s store.

Copy Text
import { createStore , combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';
 
const rootReducer = combineReducers({
    form : formReducer 
})
const store = createStore(rootReducer) 
export default store

NOTE: The key used to pass the redux-form reducer should be named form

Field Component and handleSubmit

For using redux-form Field Component, we have to build a wrapper around textInput. The wrapper executes the callbacks and uses the values returned by redux-form for tracking and updating the form state precisely. The field will pass some props to your wrapped component. These props provided by redux-form are further divided into input and meta-objects.

// FormInput.js

Copy Text
import React from 'react'
import { Text, View , TextInput } from 'react-native'
 
const FormInput = (props) => {
    const { touched , error }  = props.meta
       const isErrorVisible = () => {
        return touched && error 
            ? <Text>{error}</Text> 
            : null
    }
    return (
        <View>
            <Text>{props.label}</Text>    
            <View>
                <TextInput
			  {...props}
                    value={props.input.value}
                    onChangeText={props.input.onChange}
                    onFocus={props.input.onFocus}
                    onBlur={props.input.onBlur}
                />                
            </View>
            {isErrorVisible()}
        </View>
    )
}
 export default FormInput

isErrorVisible is responsible for showing error if the input receives an invalid value.

The value returned from the input object is passed to the defaultValue property of textInput instead of the value property. This is because we don’t want textInput to listen to the events for changing the value constantly; it may cause lagging.

Now we will create form component

// UserForm.js

Copy Text
import React from 'react'
import { ScrollView, Text, View  } from 'react-native'
import { Field, reduxForm } from 'redux-form';
import { CustomButton , FormInput } from '../../Components';
 
const UserForm = (props) => {   
    const onSubmit = (values) => {
        console.log(values)
	  props.reset()
    }
 
    return (
        <ScrollView>
            <Text>My Form</Text>
            <View>
                <Field 
                    name="fullName"
                    label="Full Name"
                    component={FormInput}
                />
                <Field 
                    name="email"
                    label="Email Id"
                    component={FormInput}
                />   
 
                <View>
                    <CustomButton 
                        onPress={props.handleSubmit(onSubmit)}
                        buttonLabel="Submit"
                    />
                </View>
            </View>
 
        </ScrollView>
    )
}
 
export default reduxForm({
    form: 'myForm'
})(UserForm)

Import reduxForm from package ‘redux-form’ to create a decorator with which you can use redux-form to connect your form component to Redux. Additionally, it takes a config parameter and helps you configure the form.

The MyFormScreen component is wrapped by reduxForm() so that it can communicate with the store. In addition, it provides props about form state and function to handle the submit process.

The handleSubmit function runs validation, and if the form is valid, then it will call props.onSubmit(data) with the form data. We can also pass the onSubmit function to handleSubmit, which will replace the submit prop

Field-Level Validation

We can provide functions for validation in the validate property of the Field Component.

Copy Text

<Field 
    name="fullName"
    label="Full Name"
    component={MyInput}
    validate={[
        (value) => value ? undefined : 'Name is required'
    ]}
/>

Resetting Form

The reset function is provided by redux-form as a prop to the MyFormScreen.

We can use this function to reset the form.

Copy Text
    const onSubmit = (values) => {
        console.log(values)
	  //structure of values will be like this- 
        // { fullName : ‘Poojan Bhatt’ , ... }
	  props.reset()
    }

Accessing the form values in another component

We will use a Modal to show the form data. It will use formValueSelector API to make it easier to connect() to form values. It will create a selector function that accepts field names and returns corresponding values from the named form.

// SuccessfullModal.js

Copy Text
import React from 'react'
import { connect } from 'react-redux'
import { formValueSelector  } from 'redux-form'
import { Modal,  Text, View } from 'react-native'
import { CustomButton } from '../../Components'
 
let SucccessfullModal = (props) => {
    const { data } = props
    return (
        <Modal
            animationType="fade"
            visible={props.visible}
            transparent={true}
        >
        	  	
        </Modal>
    )
}
 
const selector = formValueSelector('myForm')
 
SucccessfullModal = connect(state => {
    const data = selector(state,'fullName','email')
      return {data}
})(SucccessfullModal)

Here, we will pass all form fields in the selector function. It will return an object that will look like this:

Copy Text
{
  fullName: 'John',
  email: '[email protected]'
}

So this is how we can access form data in another component.

You can find the source code of the demo application here at Redux-form GitHub, where I have added two more fields and validations. You can clone the repository and play around with code.

Conclusion

So, in this part, we have covered a simple and basic redux form example for your React Native application. We will learn and explore the redux form field value and how to implement redux middleware in the next part. So, stay tuned for the next tutorial to know more about easy forms in React Native with Redux-Form! Meanwhile you can also visit React Native tutorials for more such step-by-step guides and learning tutorials.

Looking for dedicated and skilled React Native developers? Then you’re just one step closer! Get in touch with Bacancy Technology and hire React Native developer to build a next-gen cross platform application.

Build Your Agile Team

Hire Skilled Developer From Us

Subscribe for
weekly updates

newsletter

What Makes Bacancy Stand Out?

  • Technical Subject Matter Experts
  • 2500+ Projects Completed
  • 90% Client Retention Ratio
  • 12+ Years of Experience

Our developers primarily focus on navigating client's requirements with precision. Besides, we develop and innovate to deliver only the best solutions to our clients.

get in touch
[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?