React Native Keyboard Avoiding View and Request Focus

React Native Request Focus & Keyboard Avoiding View

This is an Example of Request Focus and Keyboard Avoiding View in React Native. While working with TextInput in native app development we don’t have to take care of the focus and keyboard avoiding because it is done by the app itself but in case of React Native, we have to take care of all this stuff so that we can provide a full native feel to the user.

Request Focus

Request Focus is used to set the focus to the TextInput while the keyboard is up and visible. It also helps to navigate to the next TextInput Using the following way.

How to use Request Focus

ref={ref => {
    this.currentinputReferance= ref;
}}
returnKeyType="next"
onSubmitEditing={() =>
    this.nextinputReferance && this.nextinputReferance.focus()
}

Keyboard Avoiding View

Keyboard Avoiding View is used to close the keyboard. It wraps the whole form that we made using TextInput and close the keyboard if touched outside the TextInput. It is very helpful in the case of IOS because it does have a back button to close the keyboard. This feature is by default in React Native TextInput but if we are using Request Focus then sometimes it becomes very essential to use the Keyboard Avoiding View.

KeyboardAvoidingView Use

<KeyboardAvoidingView enabled>
    //Your whole view(Form)
</KeyboardAvoidingView>

So Let’s get started with the example, In this example, we will make a Registration Form which will use TextInput with Icon and we will use Request Focus and Keyboard Avoiding View both.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependencies

To use Icon we have to install react-native-elements and react-native-vector-icons dependencies.

For installation open the terminal and jump into your project using

cd ProjectName

Run the following command

npm install react-native-elements --save
npm install react-native-vector-icons --save

This command will copy all the dependencies into your node_module directory, You can find the directories in node_module. –save is optional, it is just to update the dependencies in your package.json file.

Linking of Dependency

After the updation of React Native 0.60, they have introduced autolinking feature means we do not require to link the library but they have also mentioned that some libraries need linking and react-native-vector-icons is one of those cases. So for that, we need to link the library using

react-native link react-native-vector-icons

CocoaPods Installation

Now we need to install pods

cd ios && pod install && cd ..

Code

Open App.js in any code editor and replace the code with the following code

App.js

/*This is an Example to Use Keyboard Avoiding View and Request Focus in React Native*/
import React, { Component } from 'react';

import {
  StyleSheet,
  TextInput,
  View,
  Button,
  Text,
  KeyboardAvoidingView,
  Keyboard,
  TouchableOpacity,
  ScrollView,
} from 'react-native';
import { Icon } from 'react-native-elements';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      UserName: '',
      UserEmail: '',
      UserAge: '',
      UserAddress: '',
    };
  }

  render() {
    return (
      <View
        style={{
          flex: 1,
          backgroundColor: '#FFFFFF',
          justifyContent: 'center',
        }}>
        <ScrollView keyboardShouldPersistTaps="handled">
          <View style={{ marginTop: 100 }}>
            <KeyboardAvoidingView enabled>
              <View style={styles.SectionStyle}>
                <Icon
                  name="user"
                  type="font-awesome"
                  size={15}
                  iconStyle={{ padding: 10 }}
                  color="#413E4F"
                />

                <TextInput
                  style={{ flex: 1, color: '#413E4F' }}
                  onChangeText={UserName => this.setState({ UserName })}
                  underlineColorAndroid="#413E4F"
                  placeholder="Enter  Name"
                  placeholderTextColor="#413E4F"
                  autoCapitalize="sentences"
                  ref={ref => {
                    this._nameinput = ref;
                  }}
                  returnKeyType="next"
                  onSubmitEditing={() =>
                    this._emailinput && this._emailinput.focus()
                  }
                  blurOnSubmit={false}
                />
              </View>
              <View style={styles.SectionStyle}>
                <Icon
                  name="envelope"
                  type="font-awesome"
                  size={15}
                  iconStyle={{ padding: 10 }}
                  color="#413E4F"
                />

                <TextInput
                  style={{ flex: 1, color: '#413E4F' }}
                  onChangeText={UserEmail => this.setState({ UserEmail })}
                  underlineColorAndroid="#413E4F"
                  placeholder="Enter  Email"
                  placeholderTextColor="#413E4F"
                  autoCapitalize="sentences"
                  keyboardType="email-address"
                  ref={ref => {
                    this._emailinput = ref;
                  }}
                  returnKeyType="next"
                  onSubmitEditing={() =>
                    this._ageinput && this._ageinput.focus()
                  }
                  blurOnSubmit={false}
                />
              </View>
              <View style={styles.SectionStyle}>
                <Icon
                  name="birthday-cake"
                  type="font-awesome"
                  size={15}
                  iconStyle={{ padding: 10 }}
                  color="#413E4F"
                />

                <TextInput
                  style={{ flex: 1, color: '#413E4F' }}
                  onChangeText={UserAge => this.setState({ UserAge })}
                  underlineColorAndroid="#413E4F"
                  placeholder="Enter  Age"
                  placeholderTextColor="#413E4F"
                  autoCapitalize="sentences"
                  keyboardType="numeric"
                  ref={ref => {
                    this._ageinput = ref;
                  }}
                  onSubmitEditing={() =>
                    this._addressinput && this._addressinput.focus()
                  }
                  blurOnSubmit={false}
                />
              </View>

              <View style={styles.SectionStyle}>
                <Icon
                  name="place"
                  type="material-icons"
                  size={15}
                  iconStyle={{ padding: 10 }}
                  color="#413E4F"
                />

                <TextInput
                  style={{ flex: 1, color: '#413E4F' }}
                  onChangeText={UserAddress => this.setState({ UserAddress })}
                  underlineColorAndroid="#413E4F"
                  placeholder="Enter  Address"
                  placeholderTextColor="#413E4F"
                  autoCapitalize="sentences"
                  ref={ref => {
                    this._addressinput = ref;
                  }}
                  returnKeyType="next"
                  onSubmitEditing={Keyboard.dismiss}
                  blurOnSubmit={false}
                />
              </View>
              <TouchableOpacity
                style={styles.ButtonStyle}
                activeOpacity={0.5}
                onPress={this.UserRegisterFunction}>
                <Text
                  style={{
                    color: '#FFFFFF',
                    paddingVertical: 10,
                    fontSize: 16,
                  }}>
                  REGISTER
                </Text>
              </TouchableOpacity>
            </KeyboardAvoidingView>
          </View>
        </ScrollView>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  SectionStyle: {
    flexDirection: 'row',
    height: 40,
    marginTop: 20,
    marginLeft: 35,
    marginRight: 35,
    margin: 10,
  },

  ButtonStyle: {
    backgroundColor: '#51D8C7',
    borderWidth: 0,
    color: '#FFFFFF',
    borderColor: '#51D8C7',
    height: 40,
    alignItems: 'center',
    borderRadius: 5,
    marginLeft: 35,
    marginRight: 35,
    marginTop: 30,
  },
});

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

To run the project on an Android Virtual Device or on real debugging device

react-native run-android

or on the iOS Simulator by running (macOS only)

react-native run-ios

Output Screenshot

IOS

         

Android

         

Output in Online Emulator

That was the Request Focus and Keyboard avoiding view in React Native. If you have any doubts or you want to share something about the topic you can comment below or contact us here. The remaining components will be covered in the next article. Stay tuned!

Hope you liked it. 🙂

2 thoughts on “React Native Keyboard Avoiding View and Request Focus”

  1. Hello, i tried to add some component in this view, like an avatar and a title and i have problem, the last input is hidden by the keyboard, how can i fix that

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.