[reactjs] Clear and reset form input fields

I have a form containing various input fields and two buttons; one for submitting and one for cancelling.

<form id="create-course-form">
  <input type="text" name="course_Name" ref="fieldName">
  <input type="text" name="course_org" ref="fieldOrg">
  <input type="text" name="course_Number" ref="fieldNum">

  <input type="submit" name="saveCourse" value="Create">
  <input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse}>
</form>

What I want is to empty all inputs when the cancel button is clicked. So far I've managed to do this by using each input's ref prop.

cancelCourse(){
  this.refs.fieldName.value="";
  this.refs.fieldorg.value="";
  this.refs.fieldNum.value="";
}

However, I want to empty the input fields without having to empty each one seperately. I want something similar to this (jQuery): $('#create-course-form input[type=text]').val('');

This question is related to reactjs

The answer is


Following code should reset the form in one click.

_x000D_
_x000D_
import React, { Component } from 'react';_x000D_
_x000D_
class App extends Component {_x000D_
    constructor(props){_x000D_
     super(props);_x000D_
     this.handleSubmit=this.handleSubmit.bind(this);_x000D_
    }_x000D_
    handleSubmit(e){_x000D_
    this.refs.form.reset();_x000D_
    }_x000D_
    render(){_x000D_
        return(_x000D_
        <div>_x000D_
         <form onSubmit={this.handleSubmit} ref="form">_x000D_
                <input type="text" placeholder="First Name!" ref='firstName'/><br/<br/>_x000D_
             <input type="text" placeholder="Last Name!" ref='lastName'/><br/><br/>_x000D_
                <button type="submit" >submit</button>_x000D_
            </form>_x000D_
       </div>_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_


Why not use HTML-controlled items such as <input type="reset">


_x000D_
_x000D_
import React, { Component } from 'react'

export default class Form extends Component {
  constructor(props) {
    super(props)
    this.formRef = React.createRef()
    this.state = {
      email: '',
      loading: false,
      eror: null
    }
  }

  reset = () => {
    this.formRef.current.reset()
  }

  render() {
    return (
      <div>
        <form>
          <input type="email" name="" id=""/>
          <button type="submit">Submit</button>
          <button onClick={()=>this.reset()}>Reset</button>
        </form>
      </div>
    )
  }
}
_x000D_
_x000D_
_x000D_


state={ 
  name:"",
  email:""
}

handalSubmit = () => {
  after api call 
  let resetFrom = {}
  fetch('url')
  .then(function(response) {
    if(response.success){
       resetFrom{
          name:"",
          email:""
      }
    }
  })
  this.setState({...resetFrom})
}

Using event.target.reset() only works for uncontrolled components, which is not recommended. For controlled components you would do something like this:

import React, { Component } from 'react'

class MyForm extends Component {
  initialState = { name: '' }

  state = this.initialState

  handleFormReset = () => {
    this.setState(() => this.initialState)
  }

  render() {

    return (
      <form onReset={this.handleFormReset}>
        <div>
          <label htmlFor="name">Name</label>
          <input
            type="text"
            placeholder="Enter name"
            name="name"
            value={name}
            onChange={this.handleInputOnChange}
          />
        </div>
        <div>
          <input
            type="submit"
            value="Submit"
          />
          <input
            type="reset"
            value="Reset"
          />
        </div>
      </form>
    )
  }
}

ContactAdd.propTypes = {}

export default MyForm

This one works best to reset the form.

import React, { Component } from 'react'
class MyComponent extends Component {
  constructor(props){
    super(props)
    this.state = {
      inputVal: props.inputValue
    }
    // preserve the initial state in a new object
    this.baseState = this.state ///>>>>>>>>> note this one.
  }
  resetForm = () => {
    this.setState(this.baseState) ///>>>>>>>>> note this one.
  }
  submitForm = () => {
    // submit the form logic
  }
  updateInput = val => this.setState({ inputVal: val })
  render() {
    return (
      <form>
        <input
          onChange={this.updateInput}
          type="text
          value={this.state.inputVal} />
        <button
          onClick={this.resetForm}
          type="button">Cancel</button>
        <button
          onClick={this.submitForm}
          type="submit">Submit</button>
      </form>
    )
  }
}

/* See newState and use of it in eventSubmit() for resetting all the state. I have tested it is working for me. Please let me know for mistakes */

import React from 'react';
    
    const newState = {
        fullname: '',
        email: ''
    }
    
    class Form extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                fullname: ' ',
                email: ' '
            }
    
            this.eventChange = this
                .eventChange
                .bind(this);
            this.eventSubmit = this
                .eventSubmit
                .bind(this);
        }
        eventChange(event) {
            const target = event.target;
            const value = target.type === 'checkbox'
                ? target.type
                : target.value;
            const name = target.name;
    
            this.setState({[name]: value})
        }
    
        eventSubmit(event) {
            alert(JSON.stringify(this.state))
            event.preventDefault();
            this.setState({...newState});
        }
    
        render() {
            return (
                <div className="container">
                    <form className="row mt-5" onSubmit={this.eventSubmit}>
                        <label className="col-md-12">
                            Full Name
                            <input
                                type="text"
                                name="fullname"
                                id="fullname"
                                value={this.state.fullname}
                                onChange={this.eventChange}/>
                        </label>
                        <label className="col-md-12">
                            email
                            <input
                                type="text"
                                name="email"
                                id="email"
                                value={this.state.value}
                                onChange={this.eventChange}/>
                        </label>
                        <input type="submit" value="Submit"/>
                    </form>
                </div>
            )
        }
    }
    
    export default Form;
    

You can also do it by targeting the current input, with anything.target.reset() . This is the most easiest way!

handleSubmit(e){
 e.preventDefault();
 e.target.reset();
}

<form onSubmit={this.handleSubmit}>
  ...
</form>

Very easy:

_x000D_
_x000D_
handleSubmit(e){_x000D_
    e.preventDefault();_x000D_
    e.target.reset();_x000D_
}
_x000D_
<form onSubmit={this.handleSubmit.bind(this)}>_x000D_
  ..._x000D_
</form>
_x000D_
_x000D_
_x000D_

Good luck :)


I don't know if this is still relevant. But when I had similar issue this is how I resolved it.

Where you need to clear an uncontrolled form you simply do this after submission.

this.<ref-name-goes-here>.setState({value: ''});

Hope this helps.


To clear your form, admitted that your form's elements values are saved in your state, you can map through your state like that :

  // clear all your form
  Object.keys(this.state).map((key, index) => {
      this.setState({[key] : ""});
   });

If your form is among other fields, you can simply insert them in a particular field of the state like that:

 state={ 
        form: {
        name:"",
        email:""}
      }

      // handle set in nested objects
      handleChange = (e) =>{ 
        e.preventDefault(); 

        const newState = Object.assign({}, this.state);
        newState.form[e.target.name] = e.target.value;
        this.setState(newState);
      }

      // submit and clear state in nested object 
      onSubmit = (e) =>{ 
        e.preventDefault(); 

       var form =   Object.assign({}, this.state.form);
       Object.keys(form).map((key, index) => {
          form[key] = "" ;
        });

       this.setState({form})
      }