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={userNameInputRef}
returnKeyType="next"
onSubmitEditing={() =>
    userEmailInputRef.current &&
    userEmailInputRef.current.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 command line interface to make our React Native App.

If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:

npm uninstall -g react-native-cli @react-native-community/cli

Run the following commands to create a new React Native project

npx react-native init ProjectName

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

npx react-native init ProjectName --version X.XX.X

Note If the above command is failing, you may have old version of react-native or react-native-cli installed globally on your pc. Try uninstalling the cli and run the cli using npx.

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

Code to Request Focus and Keyboard Avoiding View

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

App.js

// React Native Keyboard Avoiding View and Request Focus
// https://aboutreact.com/example-of-request-focus-and-keyboard-avoiding-view-in-react-native/

// import React in our code
import React, {useState, createRef} from 'react';

// import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  TextInput,
  View,
  Button,
  Text,
  KeyboardAvoidingView,
  Keyboard,
  TouchableOpacity,
  ScrollView,
} from 'react-native';

const App = () => {
  const [userName, setUserName] = useState('');
  const [userEmail, setUserEmail] = useState('');
  const [userAge, setUserAge] = useState('');
  const [userAddress, setUserAddress] = useState('');

  const userNameInputRef = createRef();
  const userEmailInputRef = createRef();
  const userAgeInputRef = createRef();
  const useraddressInputRef = createRef();

  const userRegisterFunction = () => {
    alert('User Registered');
  };
  return (
    <SafeAreaView style={styles.container}>
      <ScrollView keyboardShouldPersistTaps="handled">
        <View style={styles.container}>
          <View>
            <Text style={styles.titleStyle}>
              React Native Keyboard Avoiding View and Request Focus
            </Text>
            <KeyboardAvoidingView enabled>
              <View style={styles.textInputStyle}>
                <TextInput
                  style={{flex: 1, color: '#413E4F'}}
                  onChangeText={(UserName) => setUserName(UserName)}
                  underlineColorAndroid="#413E4F"
                  placeholder="Enter  Name"
                  placeholderTextColor="#413E4F"
                  autoCapitalize="sentences"
                  ref={userNameInputRef}
                  returnKeyType="next"
                  onSubmitEditing={() =>
                    userEmailInputRef.current &&
                    userEmailInputRef.current.focus()
                  }
                  blurOnSubmit={false}
                />
              </View>
              <View style={styles.textInputStyle}>
                <TextInput
                  style={{flex: 1, color: '#413E4F'}}
                  onChangeText={
                    (UserEmail) => setUserEmail(UserEmail)
                  }
                  underlineColorAndroid="#413E4F"
                  placeholder="Enter  Email"
                  placeholderTextColor="#413E4F"
                  autoCapitalize="sentences"
                  keyboardType="email-address"
                  ref={userEmailInputRef}
                  returnKeyType="next"
                  onSubmitEditing={() =>
                    userAgeInputRef.current &&
                    userAgeInputRef.current.focus()
                  }
                  blurOnSubmit={false}
                />
              </View>
              <View style={styles.textInputStyle}>
                <TextInput
                  style={{flex: 1, color: '#413E4F'}}
                  onChangeText={
                    (UserAge) => setUserAge(UserAge)
                  }
                  underlineColorAndroid="#413E4F"
                  placeholder="Enter  Age"
                  placeholderTextColor="#413E4F"
                  autoCapitalize="sentences"
                  keyboardType="numeric"
                  ref={userAgeInputRef}
                  onSubmitEditing={() =>
                    useraddressInputRef.current &&
                    useraddressInputRef.current.focus()
                  }
                  blurOnSubmit={false}
                />
              </View>
              <View style={styles.textInputStyle}>
                <TextInput
                  style={{flex: 1, color: '#413E4F'}}
                  onChangeText={
                    (UserAddress) => setUserAddress(UserAddress)
                  }
                  underlineColorAndroid="#413E4F"
                  placeholder="Enter  Address"
                  placeholderTextColor="#413E4F"
                  autoCapitalize="sentences"
                  ref={useraddressInputRef}
                  returnKeyType="next"
                  onSubmitEditing={Keyboard.dismiss}
                  blurOnSubmit={false}
                />
              </View>
              <TouchableOpacity
                style={styles.buttonStyle}
                activeOpacity={0.5}
                onPress={userRegisterFunction}>
                <Text style={styles.buttonTextStyle}>
                  REGISTER
                </Text>
              </TouchableOpacity>
            </KeyboardAvoidingView>
          </View>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};
export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  titleStyle: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  textInputStyle: {
    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,
  },
  buttonTextStyle: {
    color: '#FFFFFF',
    paddingVertical: 10,
    fontSize: 16,
  },
});

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

1. Start Metro Bundler

First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command

npx react-native start

Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.

2. Start React Native Application

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

npx react-native run-android

or on the iOS Simulator by running (macOS only)

npx 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. 🙂

1 thought on “React Native Keyboard Avoiding View and Request Focus”

Leave a Comment

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