3

How does the "Add Day" button work without actually telling it to call the submit function when clicked.Here is the form

render (){
        return(
            <form onSubmit={this.submit}>
                <label htmlFor="resort">Resort Name</label>
                <input id="resort" type="text" defaultValue={this.props.resort} ref="resort" required/>

                <label htmlFor="date">Date</label>
                <input id="date" type="date" defaultValue={this.props.date} ref="date" required/>

                <div>
                <input id="rainy" type="checkbox" defaultChecked={this.props.rainy} ref="rainy" />
                <label htmlFor="rainy" class="weather"  >Rainy Day</label>
                </div>

                <div>
                <input id="sunny" type="checkbox" defaultChecked={this.props.sunny} ref="sunny" />
                <label htmlFor="sunny" class="weather" >Sunny Day</label>
                </div>

                <button>Add Day</button>
            </form>
            )
    }

and here is the submit function

submit(e){
        e.preventDefault();

        this.refs.resort.value='';
        this.refs.date.value='';
        this.refs.rainy.value=false;
        this.refs.sunny.value=false;

    }

Please i need a good explanation on how the button still calls the submit function just like that.

John Anisere
  • 513
  • 1
  • 3
  • 13

2 Answers2

4

This is not related to React specifically but more to HTML in general:

you have <form onSubmit={this.submit}> which means that the submit function will be called whenever the form is submitted. Which can happen for example if you press enter or if the first button in your form is clicked.

More info here: How is the default submit button on an HTML form determined?

klugjo
  • 19,422
  • 8
  • 57
  • 75
1

as @klugjo mentioned in the answer above, this isn't a question about JSX but more of fundamental HTML Knowledge

the important parts to know here is how the form tag works and how its children behave with it. the key answer to your question is the form tag and the button tag although there are some things missing in it

basically using the example below

<form onSubmit={this.handleSubmit}>
  // your code here
  <button type="submit">Add Day</button>
</form>

the button element with the type submit will always trigger the onsubmit event on its parent form(or perform the action specified in the form). You can read more about HTML forms here

Maru
  • 590
  • 5
  • 14