TextInput is provided by React native framework to implement simple text input control. Text input is one of the very basic controls of UI. Whether it is auto-complete, form, text input is a must used control in UI of application. TextInput component accepts placeholder value as props. When a user starts changing the text then the onChangeText event is triggered and when the user is done editing and hit return button, onSubmitEditing props will get invoked. TextInput component can be styled by setting style props to the component. Here is an example of the implementation of simple text input in React native:

import React from 'react';
import { View, Text, TextInput, StyleSheet } from "react-native";
class SimpleTextInput extends React.Component {
constructor(props) {
super(props);
this.state = { text: '', isSubmitted: false };
}
handleChangeText = (text) => {
this.setState({ text, isSubmitted: false });
}
handleSubmitText = () => {
this.setState({ isSubmitted: true });
}
render() {
const { text, isSubmitted } = this.state;
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder={'Type here...'}
onChangeText={this.handleChangeText}
onSubmitEditing={this.handleSubmitText}/>
<Text style={styles.text}>{isSubmitted?`User has typed: ${text}`:'User is typing'}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
alignSelf: 'stretch',
margin: 10,
padding: 10,
borderColor: '#ccc',
borderWidth: 1,
borderRadius: 5,
backgroundColor: '#eaf7fd'
},
text: {
fontSize: 14,
fontWeight: 'bold',
color: '#015169'
},
input: {
height: 40
}
});
export default SimpleTextInput;
In the above example: we have a TextInput component whose value is controlled by the state. Which means our TextInput in above example is a controlled component. Once the user starts typing we update the state with an onChangeText method. Once the user submits the value, we display the value user has typed in the text box.
Leave a Reply