-2

I have a form that has a few different type of elements (textbox, checkbox, etc.) that was created using Reactjs. I have been having a hard time trying to figure out how to clear a form. I've googled and not really sure of those solutions. I tried something like the following but found it was of no use.

What I want to happen is if the user fills out the form and decides to clear the form, once they click 'Clear Form', the form should reset. All the fields need to be blank again.

  handleClearForm(){
    this.setState({
      decisionDate: '',
      Veggies:'',
      fullName:'',
      comment:''
    }) 
  }

How can I clear a form in react? Any help would be much appreciated.

Code

OLA
  • 861
  • 2
  • 11
  • 23
  • 2
    Does this answer your question? [Clear and reset form input fields](https://stackoverflow.com/questions/43922508/clear-and-reset-form-input-fields) – justDan Nov 11 '20 at 16:34

1 Answers1

0

Check this improved code

 class App extends React.Component{
  constructor(){
    super()
    this.state = {
      decisionDate: '',
      Veggies:'',
      fullName:'',
      comment:''
    }
  }
  
    
    setdecisionDateValue (value) {
      this.setState({
        decisionDate: value
      })
    }
  
  componentDidMount(){
    $( "#decisionDate" ).datepicker({
      onSelect: this.setdecisionDateValue
    });
  }
  
  handleClearForm = () => {
    this.setState({
      decisionDate: '',
      Veggies:'',
      fullName:'',
      comment:''
    }) 
  }
  
  handleChange = (e) => {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;
    
    this.setState({[name]: value})
  }
  
  render(){
    const { decisionDate,Veggies,fullName,comment} = this.state;
    return(
     <div>
        <input type="text" name="fullName" 
        placeholder="Full Name" 
        onChange={this.handleChange} 
        value={fullName}/><br /><br />
        <input type="text" 
         name="decisionDate" 
         id="decisionDate"
         onChange={this.handleChange} 
         placeholder="MM/DD/YYYY" 
         value={this.state.decisionDate} /><br /><br />
        <textarea name="comment" 
         value={comment} 
         onChange={this.handleChange}/><br /><br />
        <input 
          type="checkbox"
          name="Veggies"
          onChange={this.handleChange} 
          checked={Veggies}
          />Veggies<br /><br />
        <button onClick={this.handleClearForm}>
         Clear Form
        </button>
      </div>
    )
  }
}

ReactDOM.render(
 <App />,
  document.getElementById("root")
)
akhtarvahid
  • 9,445
  • 2
  • 26
  • 29