Search code examples
javascriptarraysreactjsreact-state-managementreact-state

React form reset


this.state = {
  name: "",
  arr: [],
  story: ""
};

add(e) {
e.preventDefault();
this.setState({
  story: e.target.value
});
this.state.arr.push(this.state.story);
this.form.reset();

}

 <form action="">
        <input onChange={this.b} type="text" />
        <button type="submit" className="not" onClick={this.add}>
          Next
        </button>
      </form>
      <p>You did it {this.state.name}</p>

**I can't seem to figure out what is wrong with my code. I am wanting to reset state using the same function used to submit. I've tried setting state after I pushed the contents into the array but no matter what I do state remains the same. I'm a new developer so I apologize for the easy question. **


Solution

  • You can use it in two ways.

    You can get form id and reset. You need to provide id to form.

    <form action="" id="submit-form">  // id given
            <input onChange={this.b} type="text" />
            <button type="submit" className="not" onClick={this.add}>
              Next
            </button>
          </form>
          <p>You did it {this.state.name}</p>
    

    You can just use Uncontrolled ways

     add(e) {
    e.preventDefault();
    this.setState({
      story: e.target.value
    });
    this.state.arr.push(this.state.story);
      document.getElementById("submit-form").reset();}
    

    or Controlled ways.

         add(e) {
        e.preventDefault();
        this.setState({
          story: e.target.value
        });
        this.state.arr.push(this.state.story);
         this.setState({
          story: ''   //set empty value
        });
    }