Last Updated on August 1, 2019.
In this blog post, I am going to write about how to dynamically add or remove Text Input component and get corresponding values from each text input in react native.
In this react native dynamic TextInput example, I have three buttons namely add, remove and get values. Pressing add button will add a TextInput component whereas using remove button results in removal of TextInput one by one. Pressing get values button will retrieve the text entered in each TextInput as a JSON array.
Here’s the complete code of the react native example:
import React, { Component } from 'react';
import { View, TextInput, Button, StyleSheet } from 'react-native';
class MyClass extends Component {
constructor(props){
super(props);
this.state = {
textInput : [],
inputData : []
}
}
//function to add TextInput dynamically
addTextInput = (index) => {
let textInput = this.state.textInput;
textInput.push(<TextInput style={styles.textInput}
onChangeText={(text) => this.addValues(text, index)} />);
this.setState({ textInput });
}
//function to remove TextInput dynamically
removeTextInput = () => {
let textInput = this.state.textInput;
let inputData = this.state.inputData;
textInput.pop();
inputData.pop();
this.setState({ textInput,inputData });
}
//function to add text from TextInputs into single array
addValues = (text, index) => {
let dataArray = this.state.inputData;
let checkBool = false;
if (dataArray.length !== 0){
dataArray.forEach(element => {
if (element.index === index ){
element.text = text;
checkBool = true;
}
});
}
if (checkBool){
this.setState({
inputData: dataArray
});
}
else {
dataArray.push({'text':text,'index':index});
this.setState({
inputData: dataArray
});
}
}
//function to console the output
getValues = () => {
console.log('Data',this.state.inputData);
}
render(){
return(
<View>
<View style= {styles.row}>
<View style={{margin: 10}}>
<Button title='Add' onPress={() => this.addTextInput(this.state.textInput.length)} />
</View>
<View style={{margin: 10}}>
<Button title='Remove' onPress={() => this.removeTextInput()} />
</View>
</View>
{this.state.textInput.map((value) => {
return value
})}
<Button title='Get Values' onPress={() => this.getValues()} />
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
},
buttonView: {
flexDirection: 'row'
},
textInput: {
height: 40,
borderColor: 'black',
borderWidth: 1,
margin: 20
},
row:{
flexDirection: 'row',
justifyContent: 'center'
},
});
export default MyClass;
I have used arrays to generate TextInput component as well as to retrieve data from each TextInput. Following is the output of the react native example.

thanks
thanks you so must