Home > database >  How to get all inputs to reset on click of the reset form button
How to get all inputs to reset on click of the reset form button

Time:10-04

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>
  );
}

CodePudding user response:

You would need to reset all states in the onPress:

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);

  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);
            setText2(initialText);
            setText3(initialText);
            setText4(initialText);
            setText5(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>
  );
}

This will reset all states to your initial text.

CodePudding user response:

In your case only first input field is getting reset as your are changing the value of the state variable associated with the first input only. In case you want to reset all the inputs, you will need update all the state variables associated with the inputs. Or you can even have a common state variable for all the inputs fields and you can simply manage the state using that.

For example:

function SampleComponent() {
  const initialState = {input1: "", input2: ""};
  const [state, setState]  = React.useState(initialState);
  const onChange = e => {
   const { name, value } = e.target;
   setState(prevState => ({...prevState, [name]: value}));
  };
  const reset = () => setState(initialState);
      return <div>
        <label htmlFor="input1"> input 1</label>
        <input type="text" name="input1" value={state.input1} id="input1" onChange ={onChange}/>
        <label htmlFor="input2"> input 2 </label>
        <input type="text" name="input2" value={state.input2} id="input2" onChange ={onChange}  />
        <button onClick={reset}> Reset </button>
      </div>
}

// Render it
ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <SampleComponent/>
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

CodePudding user response:

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:

const initialState = {
  'First Name': '',
  'Last Name': ''
  'Favorite Food': '',
}

// just merges the "action" into the existing state
const reducer = (state, action) => ({...state, ...action});

const [state, dispatch] = useReducer(reducer, initialState);

return (
  <View>
    {
      // create a text input for each key/value in initialState
      Object.entries(initialState).map(([name, value]) => (
        <TextInput
          placeholder={name}
          value={value}
          onChangeText={newValue => dispatch({[name]: newValue})}
        />
      ))
    }
    <Button
      onPress={() => dispatch(initialState)}
      title = "Reset Form"
    />
  </View>
)

  • Related