Reset Form Input Values in React

Reset form input values in React

You need to make your inputs controlled by passing the value you store in your state then you just have to reset the state values and your component value resets.

check this sample below

handleInputChange = (e) => {
let { name, value } = e.target;
this.setState({
...this.state,
inputs: {
[name]: value
}
});

}

your component will now look like

<input name='fullName' value={this.state.inputs.fullName} onChange={this.handleInputChange} />

Your reset function will just clear the state and your input field will be empty since it's controlled via state

resetInputFields = () => {
this.setState({ inputs: {} })
}

How to reset input field from useRef in React?

You can clear the text input field by setting its value to an empty string. You can do that like this inputref.current.value = "" if you want to use uncontrolled inputs.

However, if you want to use controlled inputs you can create a state variable to track the value of the input field. For example,

const SomeComponent = () => {
const [text, setText] = useState('')

return (
<>
<input type="text" value={text} onChange={(e) => setText(e.target.value)} />
<button onClick={() => setText('')}>delete all</button>
</>
);
};

Here is a codesandbox with both implementation.

How reset form values using react bootstrap

I don't commonly use uncontrolled components, but I think you could solve this by adding setValidated(false) and event.target.reset() to the handleClickTransitionAlert, like this:

  const handleClickTransitionAlert = (event) => {
setTransitionAlert(true);
setTimeout(() => {
setTransitionAlert(false);
setValidated(false)
event.target.reset()
}, 1700);
};


Related Topics



Leave a reply



Submit