Form.submit Callback Not Getting Invoked
Solution 1:
The issue is likely calling this.form.submit()
, which handles the form submission in the DOM (instead of React), and as you say, takes it out of your control. It's refreshing the page because you don't have control over the event to call event.preventDefault()
.
Instead of this.form.submit
, you should call this.sendMessage
when the user presses enter. Presumably you're calling event.preventDefault
in sendMessage
, so you should pass the event through from onKeyDown
:
onKeyDown={e => {
if (e.keyCode === 13) {
this.sendMessage(e);
}
}}
This way, you will be handling form submission the same whether in response to the user pressing the submit button or enter.
Solution 2:
If you noticed the code in my question, I'm handling multiple events. Especially onChange
and onKeyDown
.
Couple of things we need to understand about react-bootstrap-typeahead
is
onChange
, react-bootstrap-typeahead will pass the selected object to callback whereasonKeyDown
react-bootstrap-typeahead will pass the event, from which, I will get the value usingevent.target.value
onChange
will be triggered only afteronKeyDown
. therefore, if we want to do some operation based on the selected object and that value to be used inonKeyDown
callback will not work.
To overcome this situation, I used setTimeout
also removed form element.
so my solution simply becomes
<Typeahead
id="rbt-example"
dropup={true}
ref={(typeahead) =>this.typeahead = typeahead}
onChange={this.valueChanged}
onInputChange={this.updateQuery}
onBlur={(e) =>this.updateQuery(e.target.value, e)}
onKeyDown={(e) => {
// Submit the form when the user hits enter.if (e.keyCode === 13) {
if (this.timerid) {
clearTimeout(this.timerid);
}
this.timerid = setTimeout(
() => {
this.sendMessage();
},
300
);
}
}}
options={options}
placeholder="Type your queries here..."
renderMenu={(results, menuProps) => {
// Hide the menu when there are no results.if (!results.length) {
returnnull;
}
return<TypeaheadMenu {...menuProps} options={results} />;
}}
/>
<buttononClick={() => this.sendMessage() }>Send</button>
This way, I'm calling sendMessage
method onKeyDown
and on button click. I'm also able to make use of the selected option object.
Post a Comment for "Form.submit Callback Not Getting Invoked"