How to update an array - ReactNative

What I'm trying to achieve is an Array , like this one

 infos = [{type: 'phone', val: '2222222'} {type: 'email', val: ' abc@abc.com '}] 

Here is state

 constructor(props) { super(props); this.state = { rows: [], //this is used for the add component contactDetails: [{type: '', val: ''}], // where i will add the values }; } 

So I have two TextInput

 <View> <TextInput label='Type'/> <TextInput label='Details'/> </View> 

This View can be dynamically added at the click of a button and can also be deleted. Here is my code for the add and remove buttons:

 addRow(){ this.state.rows.push(index++) this.setState({ rows: this.state.rows }) } deleteRow(key){ this.state.rows.splice(key, 1) this.setState({ rows: this.state.rows }) } <TouchableOpacity onPress={ this.addRow.bind(this) } > <Text style={{textAlign: 'center',}}>Add</Text> </TouchableOpacity> ... <TouchableOpacity onPress={ () => this.deleteRow(i) } > <Image source={require('./../img/delete.png')} style={{width:32, height: 32 }} /> </TouchableOpacity> 

How can I get its value correctly and add it to my Array ? Thanks.


Update

In my TextInput I tried to do this

 <TextInput onChangeText={(text)=>{ let cd = this.state.contactDetails; cd[i].val = text ; this.setState({cd}); }} value={this.state.contactDetails[i]} label='Details' /> 

but I always have an error undefined is not an object (evaluating 'cd[i].val = text')

0
arrays react-native react-native-android
source share
2 answers

You cannot manipulate state by declaring this.state.rows.push(index++) , but you must do this with concat() and return the value of the new variable. For example (I really don't know what the index represents in your case, but give it a try:

 addRow() { const rows = this.state.rows.concat(index++) this.setState({rows}) } 

Here is a working example that I assume you are trying to achieve: https://snack.expo.io/HySVtag6g

+1
source share

In my state, I added an array like this

 info: { type: '', val: '', } 

And then I added this to my addRow

 addRow(){ //add new array in contactDetails var arrayvar = this.state.contactDetails.slice() arrayvar.push(this.state.info) this.setState({ contactDetails: arrayvar }) //add new component row this.state.rows.push(index++); this.setState({ rows: this.state.rows}); } 

If every time the add button is contactDetails , information with Array names with empty values โ€‹โ€‹will be added to contactDetails , and then I will update the values โ€‹โ€‹of the added array.

0
source share

All Articles