Note: This question is not asking how to bind the event handlers. It's asking why, without binding, this
is not consistent in the Button
's onClick
(it refers to an object) and the Form
's onSubmit
(it's undefined
).
Full question:
I was trying to check what happens to this
object inside a method if I don't bind the method inside the constructor. What I found is that the result is different for Form and Button. Below is my code for better understanding:
const {Button, Form, Input} = Reactstrap;
class Test extends React.Component{
constructor(props){
super(props);
}
handleClick(){
console.log(this); //This gives complete information about the Button object and its properties
}
handleSubmit(e){
console.log(this); //This one is undefined
e.preventDefault();
}
render(){
return(
<React.Fragment>
<Form onSubmit={this.handleSubmit} >
<Input type="submit" name="submit">Submit</Input>
</Form>
<Button name="butt1" onClick={this.handleClick}>Click</Button>
</React.Fragment>
);
}
}
ReactDOM.render(<Test />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/reactstrap/8.4.1/reactstrap.min.js"></script>
I have checked that my question is different from this one because, in the provided question, the questioner wants to bind this
for the component while in my question, I want this
to refer to Form, just like it is referring to Button.
I am trying to find the reason for this different behavior, but I couldn't succeed. Can you people please give the reason for the same and suggest a way so that this
inside handleSubmit
starts referring to Form object?
EDIT This is what I believe the reason is, please confirm if it's correct
Since the handler for submitting was defined with the form, not for the submit button, this is why this
is undefined, because submit was clicked, not form. I think I need some bubbling capture like thing here.