W3cubDocs

/React Native

TextInput

A foundational component for inputting text into the app via a keyboard. Props provide configurability for several features, such as auto-correction, auto-capitalization, placeholder text, and different keyboard types, such as a numeric keypad.

The simplest use case is to plop down a TextInput and subscribe to the onChangeText events to read the user input. There are also other events, such as onSubmitEditing and onFocus that can be subscribed to. A simple example:

import React, { Component } from 'react';
import { AppRegistry, TextInput } from 'react-native';

export default class UselessTextInput extends Component {
  constructor(props) {
    super(props);
    this.state = { text: 'Useless Placeholder' };
  }

  render() {
    return (
      <TextInput
        style={{height: 40, borderColor: 'gray', borderWidth: 1}}
        onChangeText={(text) => this.setState({text})}
        value={this.state.text}
      />
    );
  }
}

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => UselessTextInput);

Note that some props are only available with multiline={true/false}. Additionally, border styles that apply to only one side of the element (e.g., borderBottomColor, borderLeftWidth, etc.) will not be applied if multiline=false. To achieve the same effect, you can wrap your TextInput in a View:

import React, { Component } from 'react';
import { AppRegistry, View, TextInput } from 'react-native';

class UselessTextInput extends Component {
  render() {
    return (
      <TextInput
        {...this.props} // Inherit any props passed to it; e.g., multiline, numberOfLines below
        editable = {true}
        maxLength = {40}
      />
    );
  }
}

export default class UselessTextInputMultiline extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text: 'Useless Multiline Placeholder',
    };
  }

  // If you type something in the text box that is a color, the background will change to that
  // color.
  render() {
    return (
     <View style={{
       backgroundColor: this.state.text,
       borderBottomColor: '#000000',
       borderBottomWidth: 1 }}
     >
       <UselessTextInput
         multiline = {true}
         numberOfLines = {4}
         onChangeText={(text) => this.setState({text})}
         value={this.state.text}
       />
     </View>
    );
  }
}

// skip these lines if using Create React Native App
AppRegistry.registerComponent(
 'AwesomeProject',
 () => UselessTextInputMultiline
);

TextInput has by default a border at the bottom of its view. This border has its padding set by the background image provided by the system, and it cannot be changed. Solutions to avoid this is to either not set height explicitly, case in which the system will take care of displaying the border in the correct position, or to not display the border by setting underlineColorAndroid to transparent.

Note that on Android performing text selection in input can change app's activity windowSoftInputMode param to adjustResize. This may cause issues with components that have position: 'absolute' while keyboard is active. To avoid this behavior either specify windowSoftInputMode in AndroidManifest.xml ( https://developer.android.com/guide/topics/manifest/activity-element.html ) or control this param programmatically with native code.

Props

ViewPropTypes props...

autoCapitalize?: enum('none', 'sentences', 'words', 'characters')

Can tell TextInput to automatically capitalize certain characters.

  • characters: all characters.
  • words: first letter of each word.
  • sentences: first letter of each sentence (default).
  • none: don't auto capitalize anything.

autoCorrect?: bool

If false, disables auto-correct. The default value is true.

autoFocus?: bool

If true, focuses the input on componentDidMount. The default value is false.

blurOnSubmit?: bool

If true, the text field will blur when submitted. The default value is true for single-line fields and false for multiline fields. Note that for multiline fields, setting blurOnSubmit to true means that pressing return will blur the field and trigger the onSubmitEditing event instead of inserting a newline into the field.

caretHidden?: bool

If true, caret is hidden. The default value is false.

defaultValue?: string

Provides an initial value that will change when the user starts typing. Useful for simple use-cases where you do not want to deal with listening to events and updating the value prop to keep the controlled state in sync.

editable?: bool

If false, text is not editable. The default value is true.

keyboardType?: enum('default', 'email-address', 'numeric', 'phone-pad', 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search')

Determines which keyboard to open, e.g.numeric.

The following values work across platforms:

  • default
  • numeric
  • email-address
  • phone-pad

maxLength?: number

Limits the maximum number of characters that can be entered. Use this instead of implementing the logic in JS to avoid flicker.

multiline?: bool

If true, the text input can be multiple lines. The default value is false.

onBlur?: function

Callback that is called when the text input is blurred.

onChange?: function

Callback that is called when the text input's text changes.

onChangeText?: function

Callback that is called when the text input's text changes. Changed text is passed as an argument to the callback handler.

onContentSizeChange?: function

Callback that is called when the text input's content size changes. This will be called with { nativeEvent: { contentSize: { width, height } } }.

Only called for multiline text inputs.

onEndEditing?: function

Callback that is called when text input ends.

onFocus?: function

Callback that is called when the text input is focused.

onLayout?: function

Invoked on mount and layout changes with {x, y, width, height}.

onScroll?: function

Invoked on content scroll with { nativeEvent: { contentOffset: { x, y } } }. May also contain other properties from ScrollEvent but on Android contentSize is not provided for performance reasons.

onSelectionChange?: function

Callback that is called when the text input selection is changed. This will be called with { nativeEvent: { selection: { start, end } } }.

onSubmitEditing?: function

Callback that is called when the text input's submit button is pressed. Invalid if multiline={true} is specified.

placeholder?: node

The string that will be rendered before text input has been entered.

placeholderTextColor?: color

The text color of the placeholder string.

returnKeyType?: enum('done', 'go', 'next', 'search', 'send', 'none', 'previous', 'default', 'emergency-call', 'google', 'join', 'route', 'yahoo')

Determines how the return key should look. On Android you can also use returnKeyLabel.

Cross platform

The following values work across platforms:

  • done
  • go
  • next
  • search
  • send

Android Only

The following values work on Android only:

  • none
  • previous

iOS Only

The following values work on iOS only:

  • default
  • emergency-call
  • google
  • join
  • route
  • yahoo

secureTextEntry?: bool

If true, the text input obscures the text entered so that sensitive text like passwords stay secure. The default value is false.

selectTextOnFocus?: bool

If true, all text will automatically be selected on focus.

selection?: {start: number, end: number}

The start and end of the text input's selection. Set start and end to the same value to position the cursor.

selectionColor?: color

The highlight and cursor color of the text input.

style?: Text#style

Note that not all Text styles are supported, see Issue#7070 for more detail.

Styles

value?: string

The value to show for the text input. TextInput is a controlled component, which means the native value will be forced to match this value prop if provided. For most uses, this works great, but in some cases this may cause flickering - one common cause is preventing edits by keeping value the same. In addition to simply setting the same value, either set editable={false}, or set/update maxLength to prevent unwanted edits without flicker.

androiddisableFullscreenUI?: bool

When false, if there is a small amount of space available around a text input (e.g. landscape orientation on a phone), the OS may choose to have the user edit the text inside of a full screen text input mode. When true, this feature is disabled and users will always edit the text directly inside of the text input. Defaults to false.

androidinlineImageLeft?: string

If defined, the provided image resource will be rendered on the left.

androidinlineImagePadding?: number

Padding between the inline image, if any, and the text input itself.

androidnumberOfLines?: number

Sets the number of lines for a TextInput. Use it with multiline set to true to be able to fill the lines.

androidreturnKeyLabel?: string

Sets the return key to the label. Use it instead of returnKeyType.

androidtextBreakStrategy?: enum('simple', 'highQuality', 'balanced')

Set text break strategy on Android API Level 23+, possible values are simple, highQuality, balanced The default value is simple.

androidunderlineColorAndroid?: color

The color of the TextInput underline.

iosclearButtonMode?: enum('never', 'while-editing', 'unless-editing', 'always')

When the clear button should appear on the right side of the text view.

iosclearTextOnFocus?: bool

If true, clears the text field automatically when editing begins.

iosdataDetectorTypes?: enum('phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all'), [enum('phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all')]

Determines the types of data converted to clickable URLs in the text input. Only valid if multiline={true} and editable={false}. By default no data types are detected.

You can provide one type or an array of many types.

Possible values for dataDetectorTypes are:

  • 'phoneNumber'
  • 'link'
  • 'address'
  • 'calendarEvent'
  • 'none'
  • 'all'

iosenablesReturnKeyAutomatically?: bool

If true, the keyboard disables the return key when there is no text and automatically enables it when there is text. The default value is false.

ioskeyboardAppearance?: enum('default', 'light', 'dark')

Determines the color of the keyboard.

iosonKeyPress?: function

Callback that is called when a key is pressed. This will be called with { nativeEvent: { key: keyValue } } where keyValue is 'Enter' or 'Backspace' for respective keys and the typed-in character otherwise including ' ' for space. Fires before onChange callbacks.

iosselectionState?: DocumentSelectionState

An instance of DocumentSelectionState, this is some state that is responsible for maintaining selection information for a document.

Some functionality that can be performed with this instance is:

  • blur()
  • focus()
  • update()

You can reference DocumentSelectionState in vendor/document/selection/DocumentSelectionState.js

iosspellCheck?: bool

If false, disables spell-check style (i.e. red underlines). The default value is inherited from autoCorrect.

Methods

isFocused():

Returns true if the input is currently focused; false otherwise.

clear()

Removes all text from the TextInput.

© 2015–2017 Facebook Inc.
Licensed under the Creative Commons Attribution 4.0 International Public License.
https://facebook.github.io/react-native/docs/textinput.html