Dynamically get text from code generated textboxes - duyluandethuong/react-native-tips-tricks GitHub Wiki

Code to create new textbox and add it to the render function

     var newIngredientRow = (<View key={newIngredientKey} style={lugagistyle.col}>
								<TextInput
								    style={[lugagistyle.formInput, lugagistyle.col8]}
								    value={this.state.searchString}
								    onChange={this.setTextInputSelftValue.bind(this, newTextIngredientKey)}
								    key={newTextIngredientKey}
								    placeholder='Nhập tên nguyên liệu vào đây'/>**
								{deleteIngredientButton}
								<View style={lugagistyle.separator}/>
							</View>);

	//Add the new ingredient to the global array
	totalIngredientRow.push(newIngredientRow);
	
	//Set state to render it
	this.setState({ 
		ingredientListUI: totalIngredientRow 
	});

From this code, you can see that I have a TextInput component inside a bigger custom component newIngredientRow, and its onChange event is this.setTextInputSelftValue.bind(this, newTextIngredientKey). Note that the array totalIngredientRow is my global array to contains all the code-generated custom components, you can use state instead.

For each of the TextBox, I assign a unique key for it by using prop key={newTextIngredientKey}. This newTextIngredientKey can be anything you like, say 'textbox' + a number, 'hahaha' + number... Key is important for us to pin point the exact component that we need to access.

The function setTextInputSelftValue is as follow:

setTextInputSelftValue: function(textIngredientKey, event) {
  	for (var i=0; i < totalIngredientRow.length; i++) {
		if (totalIngredientRow[i].props.children[0].key == textIngredientKey) {
			totalIngredientRow[i].props.children[0].props.value = event.nativeEvent.text; //Set the text value for the textbox whenever the user start typing
		}
	}
},

What this function does is that it goes to my global array (or state, if you want) to look up the TextInput component. Since each of my custom component has a TextInput component inside it as the first element, so the index will be 0. That is why we have totalIngredientRow[i].props.children**[0]**. In your case, the index may be different, depending on the location of the TextInput relative to its parent structure.

Then, to set or get the value of a TextInput, we will use .props.value. Simple as that.

From the two codes above, we can dynamically assigned the "value" property for each TextInput whenever the user start typing.

If you want to get text value from all textboxes, say to serialize a form before submit to a server, then the only thing you need to do now is loop through all the TextInput in the bigger global array and get the .props.value of each of them.

⚠️ **GitHub.com Fallback** ⚠️