Reputation: 312
SO I thought I have a good grasp in callbacks and this
until I started to learning event handlers in react.
I know that the code below has a function onFormSubmit
which is a callback function and gets called when the user submits the form. But as a callback function is a function which is passed to another function as an argument I want to know which function is calling this function.
class SearchBar extends React.Component{
state={term:""};
onFormSubmit = ()=>{
//do something with callback
}
render(){
return (
<div className="search-bar ui segment">SearchBar
<form onSubmit={this.onFormSubmit} className="ui form">
<div className="field">
<label>Video Search</label>
<input
type="text"
value={this.state.term}
onChange={this.onInputChange}
/>
</div>
</form>
</div>
);
}
}
Upvotes: 0
Views: 69
Reputation: 109
Your search bar class has some jsx that will be rendered . Within this JSX you have a property that is called onSubmit
. This property is then assigned a JSX expression which is of type function. The DOM elements have EventListeners they can attach handlers. If you were to assign an add an eventListener to an element using vanilla JS it would go something like this.
let el = document.getElementById('test')
el.addEventListener('click',yourHandlerFunction);
React is only taking your function and wrapping it in a SyntheticEvent then attaching it to the element where the property is located. In this case your form element. It's working like any other DOM event except for the fact that you its wrapped in a SyntheticEvent. The element is now listening to the event you described, in your case onSubmit and whenever this this action is performed the event gets notified and calls the appropriate handler function. It resembles a lot to the Observer Pattern .
check out how events get attached in plain HTML properties
Also you might be interested in the Event Interface as it the base of all other events.
Upvotes: 2
Reputation: 39
HTML have build in function hooks that are triggered when certain event happen. say to which you can attach the callback method of your which is called automatically by the browser whenever a click event happen(in our case).
so for given your case the form onSubmit callback is called when the form get submitted browser checks if there are any callbacks attached to onSubmit hook and if so if executes the same.
Upvotes: 0