I have a controlled React input component and I am formatting the input as shown in onChange code.
<input type="TEL" id="applicantCellPhone" onChange={this.formatPhone} name="applicant.cellPhone" value={this.state["applicant.cellPhone"]}/>
And then my formatPhone function is like this
formatPhone(changeEvent) {
let val = changeEvent.target.value;
let r = /(\D+)/g,
first3 = "",
next3 = "",
last4 = "";
val = val.replace(r, "");
if (val.length > 0) {
first3 = val.substr(0, 3);
next3 = val.substr(3, 3);
last4 = val.substr(6, 4);
if (val.length > 6) {
this.setState({ [changeEvent.target.name]: first3 + "-" + next3 + "-" + last4 });
} else if (val.length > 3) {
this.setState({ [changeEvent.target.name]: first3 + "-" + next3 });
} else if (val.length < 4) {
this.setState({ [changeEvent.target.name]: first3 });
}
} else this.setState({ [changeEvent.target.name]: val });
}
I start facing the problem when I try to delete/add a digit somewhere in the middle and then cursor immediately moves to the end of the string.
I saw a solution at solution by Sophie, but I think that doesn't apply here as setState will cause render anyways. I also tried to manipulate caret position by setSelectionRange(start, end), but that didn't help either. I think setState that causes render is making the component treat the edited value as final value and causing cursor to move to the end.
Can anyone help me figuring out how to fix this problem?