I am learning react and react native and trying to build a basic form. I want what is inputted in the inputs to be displayed below. Then on clicking the reset form button have all the inputs reset.
It is only resetting the first input and I can feel myself slowly grasping react but I am stuck on this last part. If someone could tell me how to fix this and explain the reasoning behind it it would be greatly appreciated.
Cheers
import React, {useState} from 'react';
import { Text, View, StyleSheet, Button, InputAccessoryView, TextInput} from 'react-native';
export default function Form() {
const inputAccessoryViewID = 'uniqueID';
const initialText='';
const[text, setText] = useState(initialText);
const[text2, setText2] = useState(initialText);
const[text3, setText3] = useState(initialText);
const[text4, setText4] = useState(initialText);
const[text5, setText5] = useState(initialText);
var onPressed = () =>{
setText(initialText);
}
return (
<View style={styles.container}>
<View style={styles.input}>
<TextInput inputAccessoryViewID={inputAccessoryViewID} onChangeText={setText} value={text} placeholder={'First and Last Name'}/>
</View>
<View style={styles.input}>
<TextInput keyboardType="numeric" inputAccessoryViewID={inputAccessoryViewID} onChangeText={setText2} value={text2} placeholder={'Phone Number'}/>
</View>
<View style={styles.input}>
<TextInput inputAccessoryViewID={inputAccessoryViewID} onChangeText={setText3} value={text3} placeholder={'Program'}/>
</View>
<View style={styles.input}>
<TextInput inputAccessoryViewID={inputAccessoryViewID} onChangeText={setText4} value={text4} placeholder={'Favourite Food'}/>
</View>
<View style={styles.input}>
<TextInput inputAccessoryViewID={inputAccessoryViewID} onChangeText={setText5} value={text5} placeholder={'Hobby'}/>
</View>
<InputAccessoryView nativeID={inputAccessoryViewID}>
<Button
onPress={() => setText(initialText)}
title = "Reset Form"
/>
</InputAccessoryView>
<Text style={styles.displayText}>
{text}
</Text>
<Text style={styles.displayText}>
{text2}
</Text>
<Text style={styles.displayText}>
{text3}
</Text>
<Text style={styles.displayText}>
{text4}
</Text>
<Text style={styles.displayText}>
{text5}
</Text>
</View>
);
}
2
Answers
You would need to reset all states in the
onPress
:This will reset all states to your initial text.
You could simplify your form state tracking and make it easier to reset by using useReducer instead of useState. With useReducer your entire form state could live in one place instead of being spread across a dozen different state variables.
If you go this route you can reset the form with a single call to
dispatch(initialState)
.Psuedocode: