'React.JS Cancelling onBlur
I need to 'cancel' the onBlur event on a form field. So, basically I prevent the user to leave the field under certain conditions.
I tried to do literally cancel onBlur (in a way that the field woudln't lose focus). But it looks like onBlur is not cancellable.
Another approach looked logical to me: set the focus back again after the control loses it. So I did this:
onActivateField =()=> {
console.log("ActivateField");
}
leavingField = (e) => {
this.me.focus();
console.log("tried to focus control...",this.me);
}
return (
<input type="text"
ref = {elem => this.me = elem }
onBlur = {this.leavingField}
onFocus={this.onActivateField}>
</input>)
Well this didn't work. And this.me is a valid element.
So, I thought that maybe if I had another element X to receive the focus, I could interpret the onFocus of element X as losing focus on my field.
I tried with a div, like this:
onActivateField =()=> {
console.log("ActivateField");
}
leavingField = (e) => {
this.me.focus();
console.log("tried to focus control...",this.me);
}
return (
<div onFocus={this.leavingField}>
<input type="text"
ref = {elem => this.me = elem }
onBlur = {this.leavingField}
onFocus={this.onActivateField}>
</input>
</div>)
of course, this woudln't work - the <input> is inside the <div>, so its onFocus will be triggered when the input's onFocus is triggered.
Then I added a dummy <button> et voilà it worked!
return (
<div onFocus={this.leavingField}>
<input type="text"
ref = {elem => this.me = elem }
placeholder={this.props.placeholder}
required={isMandatory}
onFocus={this.onActivateField}
></input>
<button></button> //<-- empty button
</div>
)
First I added the onFocus on the button and it worked, but then went back and added it again on the div.
You will see that this will work perfectly. But the button is not good for my solution, because I want the user to be able to tab around between fields accross the site without setting focus on any dummy control on the middle.
Also setting display:none on the button is not usefull because then it won't receive focus anyway.
But, if I remove the button, puff! It goes back to nothing. Any suggestions?
Thanks! I'll keep experimenting, I'll let you know if I find out a way.
EDIT:
I have found a way that works partially, having an extra control in the div. It works good if you <TAB> out of the field, but it doesn't work in other situations (like clicking somewhere else on the page). I am still going for it. If this question must be closed, it's ok. If it's still open by the time I have an answer, I'll post it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
