1

I'm trying to clear the form onClick with react. The event triggers, but when I try to setState to " " it tells me cannot set state of undefined.

I've tried setting the state to empty in several ways.

onHandleChange(e) {
this.setState({
input: e.target.value
});
}

clearForm(e) {
e.preventDefault();
const input = this.state.input;
console.log("input", input);
this.setState({
  input: ""
});
}

I've also tried to do it inline, with onClick={(this.form.elements["text-input"].value = "")}.

<button
  className="reset btn btn-danger"
  type="reset"
  id="resetInput"
  value="reset"
  onChange={this.onHandleChange}
  onClick={this.clearForm}
>
  Reset
</button>

My expected output is that the value of the input should be nothing. Empty string. However, that's not happening... i'm not resetting the state.

Klara13
  • 35
  • 4
  • 4
    I don't see input textbox, all i see is button on which you have applied `onChange` which should not be there. – tarzen chugh Sep 10 '19 at 12:07
  • Possible duplicate of [React - uncaught TypeError: Cannot read property 'setState' of undefined](https://stackoverflow.com/questions/32317154/react-uncaught-typeerror-cannot-read-property-setstate-of-undefined) – Heretic Monkey Sep 10 '19 at 12:45

3 Answers3

0

This happens because you are not binding this correctly to clearForm function.

Cannot set State of undefined. This error means in this.state, this is undefined

Use arrow function to correctly bind this context.

Try this code

clearForm = (e) => {
tarzen chugh
  • 10,561
  • 4
  • 20
  • 30
0

Try This Code

<script>
    $(document).ready(function(){
        $('#btnClear').click(function(){                
            if(confirm("Want to clear?")){
                /*Clear all input type="text" box*/
                $('#form1 input[type="text"]').val('');
            }                   
        });
    });
</script>
0

You can set state for all the values of the form input to be empty strings on click of that clear button.

Harshit Agarwal
  • 2,308
  • 2
  • 15
  • 23