• Articles
  • Tutorials
  • Interview Questions

React Native Text Input

React Native Text Input

In this blog, we will explore everything you need to know about React Native TextInput, including its basics, customization, recording user input, and more.

Watch this video on ReactJS Full Course:

Getting started with TextInput

Before we dive into the details, let’s first understand what TextInput is and how it works.

The TextInput element serves as a fundamental module within React Native, providing the capability for users to input textual content into your application. It presents a singular line input field, facilitating the acquisition of various forms of data, including but not limited to names, email addresses, phone numbers, and additional information.

Here’s an example of how you can use TextInput in your React Native app

import React, { useState } from 'react';
import { TextInput, View } from 'react-native';
const App = () => {
  const [text, setText] = useState('');
  return (
   <View>
      <TextInput
        onChangeText={text => setText(text)}
        value={text}
        placeholder="Enter your name"
      />
    </View>
  );
};
export default App;

In this example, we incorporate the TextInput and View modules from the React Native library. Subsequently, we established a functional component named App, which encompasses a TextInput module. Additionally, we employ the useState hook to regulate the state of the text input.

The onChangeText property is a callback function that is invoked each time the user inputs text into the designated field. The entered text is then passed as an argument to the setText function, which is responsible for modifying the state of the text input component.

The value proposition is employed to establish the initial value of the text input. In this illustration, we assign the initial value as an empty string.

The placeholder attribute is utilized to present a suggestive indication to the user regarding the expected input type in the text input field.

Now that we possess a fundamental comprehension of the functioning of the TextInput component, let us progress to the subsequent section, wherein we shall delve into the fundamentals of TextInput.

Thinking of getting a certification in React JS? Here is the React JS Course for you to enroll in!

TextInput basics

Text Input basics

In this section, we will explore the basic features of TextInput, including its props and methods.

Props

The TextInput component in React Native enables users to input text into your app. It provides various fundamental props that let you customize how it looks and behaves. Here are some of the frequently utilized props.

  • autoCapitalize – This prop controls the capitalization of the text input. It can be set to “none”, “sentences”, “words”, or “characters”.
  • autoCorrect – This prop controls whether the text input should automatically correct spelling mistakes.
  • defaultValue – This property establishes the default value for the text input.
  • editable – This prop controls whether the text input is editable or not.
  • keyboardType –The type of keyboard displayed upon tapping the text input can be determined by setting this property. It offers various options such as “default”, “numeric”, “email-address”, “phone-pad”, and others.
  • maxLength – The maxLength property establishes the upper limit for the character count that users can input into the text input field.
  • multiline – The prop determines if the text input should permit multiple lines of text.
  • onBlur – This prop is a callback function that gets called when the text input loses focus.
  • onChange – This prop is a callback function that gets called whenever the text input changes.
  • onFocus – It is a callback function that gets called when the text input gains focus.
  • placeholder – This type of prop sets the placeholder text to be displayed when the text input is empty.
  • secureTextEntry – The text input’s hide/show feature is controlled by this prop.

These properties offer fundamental functionality for TextInput, enabling you to tailor its behavior and appearance to align with the requirements of your application. Through the utilization of these properties, you have the ability to construct text input fields that are conducive to user-friendliness, intuitiveness, and responsiveness in accommodating user input.

Get 100% Hike!

Master Most in Demand Skills Now !

For example, you can set the keyboardType prop to “email-address” to ensure that the keyboard displayed when the user taps on the text input is optimized for entering email addresses. Similarly, you can set the maxLength prop to limit the number of characters that the user can enter into the text input, ensuring that the input stays within a predefined range.

Preparing for a Job Interview? Check out our blog on React Interview Questions!

Methods

In addition to its fundamental properties, TextInput possesses several methods that facilitate programmatic interaction. These methods offer supplementary capabilities for TextInput, enabling you to govern its behavior and promptly respond to user input. Presented below are some of the frequently utilized methods:

  • focus() – This method sets the focus to the text input, making the keyboard appear. The focus() method proves to be of great utility in cases where it is necessary to programmatically establish focus on a text input, such as when the user navigates to a specific screen or performs a specific action. An illustrative instance would be the utilization of the focus() method to direct focus to a search bar when the user taps on a search icon, thereby enabling them to commence typing their search query promptly.
  • blur() – This method removes the focus from the text input, hiding the keyboard. In situations where it is required to remove attention from a text input field, the blur() technique is useful. This can happen if a user interacts with something outside the input field or switches to another screen. For instance, when a user presses the “cancel” button or navigates to a different screen, the blur() method can be used to hide the keyboard and return the focus to a text input field.
  • clear() – This method clears the text input. The clear() method proves to be beneficial in cases where there is a need to programmatically remove the content entered in a text input. This situation often arises when the user submits a form or carries out a particular action. An instance where the clear() method is commonly employed is when a user taps on a designated “clear” button associated with a search bar, resulting in the removal of the existing search query and enabling the initiation of a fresh search.
  • isFocused() – The isFocused() method serves the purpose of indicating the current focus state of a text input. It returns a Boolean value of true if the text input is currently focused and false if it is not. This method proves valuable when the need arises to ascertain the focus status of a text input, enabling the execution of conditional logic based on that state. One practical application of the isFocused() method is to selectively display a “search” button, contingent upon the current focus being on the search bar, thus indicating the user’s active search activity.

Using these techniques, one may create text input fields with more dynamism and responsiveness in a React Native application. These approaches enable you to control the focus state of a text input, respond quickly to user input, and create a more engaging and interactive user interface.

To get in-depth knowledge of Reactjs check out our ReactJS Tutorial!

Customization

Text Input Customization

An advantageous aspect of React Native TextInput is its capacity for customization to align with the specific requirements of your application. Within this section, we shall delve into several methods through which you can tailor TextInput according to your preferences.

Styling

The styling of TextInput can be accomplished through the utilization of the style prop, which grants the ability to apply CSS-like styles to the component. Presented below is an illustrative instance showcasing the usage of the style prop to personalize the appearance of TextInput.

<TextInput
  style={{
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    paddingHorizontal: 10,
    borderRadius: 5,
  }}
  onChangeText={text => setText(text)}
  value={text}
  placeholder="Enter your name"
/>

In this particular instance, we implement various styles to the TextInput element, encompassing the adjustment of its height, border color, border width, padding, and border radius.

Additionally, the StyleSheet API can be utilized to establish styles for the TextInput element in the following manner.

const styles = StyleSheet.create({
  input: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    paddingHorizontal: 10,
    borderRadius: 5  },
});
<TextInput
  style={styles.input}
  onChangeText={text => setText(text)}
  value={text}
  placeholder="Enter your name"
/>

Icons

To enhance the visual appeal and improve user-friendliness of the TextInput component, you can incorporate icons into it. React Native provides various icon libraries such as react-native-vector-icons and react-native-elements, allowing you to add icons to the TextInput.

Here’s a demonstration of how to utilize react-native-vector-icons for adding an icon to TextInput.

import Icon from 'react-native-vector-icons/FontAwesome';
<TextInput
  style={styles.input}
  onChangeText={text => setText(text)}
  value={text}
  placeholder="Enter your name"
  leftIcon={<Icon name="user" size={24} color="black" />}
/>

In this case, we integrate the Icon component sourced from react-native-vector-icons/FontAwesome and utilize it to add a user icon on the left-hand side of the TextInput. The size and color of the icon are specified by the size and color properties.

Recording a User’s Input

The act of documenting a user’s input holds potential value for diverse purposes, including analytics, debugging, and the mere preservation of user data. Within the framework of React Native, the onChangeText attribute of TextInput can be employed to seize user input, subsequently storing it in a state variable or transmitting it to a server for the purpose of storage.

Here’s an example of how you can record a user’s input in a state variable:

import React, { useState } from 'react';
import { View, TextInput, Button } from 'react-native';
const InputRecorder = () => {
  const [inputValue, setInputValue] = useState('');
  const handleInputChange = (text) => {
    setInputValue(text);
  };
  const handleSave = () => {
    // Save the inputValue to a server or local storage
    console.log('Input value:', inputValue);
  };
  return (
    <View>
      <TextInput
        style={{ height: 50, borderColor: 'gray', borderWidth: 1 }}
        onChangeText={handleInputChange}
        value={inputValue}
      />
      <Button title="Save" onPress={handleSave} />
    </View>
  );
};
export default InputRecorder;

In this illustration, a state variable named “inputValue” is created to store the input provided by the user. The useState hook is utilized to establish the state variable, while the setInputValue function is employed to update the state whenever the user enters text into the input field.

The handleInputChange function is invoked whenever the user types into the input field, and its purpose is to update the “inputValue” state with the new value entered.

When the user clicks the “Save” button, the handleSave function is triggered. In this specific instance, the “inputValue” is logged to the console; however, it could also be sent to a server for storage or saved in local storage, depending on the intended functionality.

To capture the user’s input, the onChangeText prop of the TextInput component is employed, with the handleInputChange function being passed as its value. This function is called whenever the user enters text into the input field, ensuring that the “inputValue” state is updated with the latest value.

Finally, the TextInput and Button components from React Native are used to display the input field and the “Save” button. The value prop of the text input is assigned the “inputValue” state in order to exhibit the current value of the input field.

By utilizing the onChangeText prop and state variables, you can effortlessly capture and retain user input within your React Native application. This functionality proves beneficial for a multitude of use cases, including analytics, debugging, and user data storage.

Text fields with React Native Paper

React Native Paper is a popular UI library for React Native that provides a rich set of components to help you build beautiful and responsive user interfaces. One of the components it provides is TextInput, a customizable text input field that offers additional features and styling options compared to the standard React Native TextInput.

Here’s an example of how you can use TextInput from React Native Paper:

import React, { useState } from 'react';
import { View } from 'react-native';
import { TextInput, Button } from 'react-native-paper';
const PaperTextInput = () => {
  const [text, setText] = useState('');
  const handleTextInputChange = (inputText) => {
    setText(inputText);
  };
  const handleButtonPress = () => {
    console.log(`Input value: ${text}`);
  };
  return (
    <View>
      <TextInput
        label="Enter some text"
        value={text}
        onChangeText={handleTextInputChange}
        mode="outlined"
      />
      <Button mode="contained" onPress={handleButtonPress}>
        Save
      </Button>
    </View>
  );
};
export default PaperTextInput;

In this example, we import the TextInput and Button components from React Native Paper. We also use the useState hook to create a state variable text to store the user’s input.

The handleTextInputChange function is called whenever the user types into the TextInput. It updates the text state variable with the new value of the input field.

The TextInput component is presented, wherein the label prop is assigned the value of “Enter some text”, the value prop is assigned the text state variable, the onChangeText prop is assigned the handleTextInputChange function, and the mode prop is assigned the value of “outlined”. The mode prop determines the styling of the TextInput as outlined, resulting in the addition of a border and enhanced visibility.

We also display a Button component with the mode prop set to “contained” and the onPress prop set to the handleButtonPress function. The onPress prop specifies what should happen when the user presses the button. In this case, we simply log the text state variable to the console.

The utilization of TextInput from React Native Paper empowers you to fashion personalized text input fields, encompassing supplementary functionalities and style alternatives surpassing those offered by the conventional React Native TextInput. This proficiency facilitates the creation of captivating and user-centric forms and input fields within your React Native application.

Conclusion 

In summary, the React Native TextInput component demonstrates itself as a versatile and potent tool for constructing text input fields within your mobile application. Through its array of customizable properties and methods, you have the capability to design user-friendly and intuitive forms that promptly react to user input. Regardless of whether you are developing a straightforward login screen or an intricate data entry form, the React Native TextInput component offers the adaptability and functionality required to fashion a triumphantly operational mobile application.

If you have any questions regarding the topic, visit our community page for the answers.

Course Schedule

Name Date Details
Web Development Courses 22 Jun 2024(Sat-Sun) Weekend Batch
View Details
Web Development Courses 29 Jun 2024(Sat-Sun) Weekend Batch
View Details
Web Development Courses 06 Jul 2024(Sat-Sun) Weekend Batch
View Details

About the Author

Techical Research Analyst - Front End Development

As a Technical Research Analyst, Kislaya specializes in Front End Development. He is a Full Stack Developer, known for crafting scalable architectures and user-centric interfaces. He has a massive international client base and is an expert in cloud computing, Linux, and Java Script, personifying a commitment to quality and information sharing.