Files
react-native/docs/HandlingTextInput.md
Kevin Lacker bfb4c054f4 Make "The Basics" flow like a linear tutorial
Summary: Closes https://github.com/facebook/react-native/pull/8429

Differential Revision: D3487369

Pulled By: lacker

fbshipit-source-id: 59b32f2a2a67370192c91dc43da3d4b76a43b810
2016-06-26 12:43:25 -07:00

1.8 KiB

id, title, layout, category, permalink, next
id title layout category permalink next
handling-text-input Handling Text Input docs The Basics docs/handling-text-input.html using-a-scrollview

TextInput is a basic component that allows the user to enter text. It has an onChangeText prop that takes a function to be called every time the text changed.

This example shows how to count the number of characters that have been typed in a box.

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

class CharacterCounter extends Component {
  constructor(props) {
    super(props);
    this.state = {text: ''};
  }

  render() {
    return (
      <View style={{padding: 10}}>
        <TextInput
          style={{height: 40}}
          placeholder="Pleeeease type on me!"
          onChangeText={(text) => this.setState({text})}
        />
        <Text style={{padding: 10}}>{this.state.text.length}</Text>
      </View>
    );
  }
}

AppRegistry.registerComponent('CharacterCounter', () => CharacterCounter);

In this example, we store text in the state, because it changes over time.

There are a lot more advanced things you might want to do with a text input. For example, you could validate the text inside while the user types. For more detailed examples, see the React docs on controlled components, or the reference docs for TextInput.

Text input is probably the simplest example of a component whose state naturally changes over time. Next, let's look at another type of component like this is one that controls layout, and learn about the ScrollView.