How to dynamically add/delete form in react/react-native
First create a state array which will represent your form structure, now it can be fetched your any API, or you can create it manually
this.state = {
array: [{
studentName: 'John doe',
uid: 1
}]
}
Loop over the same state array
{
array.map((item, index) => {
return (
<View style={{ margin: 5, padding: 10, }}>
<TextInput placeholder='Student name'
value={item.studentName}
style={{ borderRadius: 4, borderWidth: 1, borderColor: '#212121', padding: 8 }}
onChangeText={text => {
this.setState({ array: array.map((c, innerIndex) => innerIndex === index ? { ...c, studentName: text } : c) })
}} />
<TextInput placeholder='Student UID'
value={item.uid}
style={{ borderRadius: 4, borderWidth: 1, borderColor: '#212121', padding: 8, marginTop: 5 }}
onChangeText={text => {
this.setState({ array: array.map((c, innerIndex) => innerIndex === index ? { ...c, uid: text } : c) })
}} />
<Text style={{
alignSelf: 'flex-start', borderRadius: 4,
padding: 3, marginTop: 5, backgroundColor: 'red', color: 'white'
}} onPress={() => {
const filterList = array.filter((item, inner) => inner != index)
this.setState({ array: filterList })
}}>
Remove
</Text>
</View>
)
})
}
When you want to add one more field create a handler, which will simply add an empty object to your state array, as you have already looped over state array so when ever state array changes your form changes
<Text style={{ padding: 16, textAlign: 'center', backgroundColor: 'black', color: 'white' }} onPress={() => {
this.setState({
array: [...array, {
studentName: '',
uid: ''
}]
})
}}>
Add
</Text>
Complete App.js code is available here