I am using the TagPicker
which has the event onKeyDown
with signature (ev: React.KeyboardEvent<HTMLElement>) => void
Is there a way I can use this event to only allow lower-case letters and the dash -
symbol? Ideally I would like to transform upper-case letters to lower-case automatically.
I have found a solution for this, TagPicker
has an inputProps
attribute which allows to hook up to the input events. Once I found this out, this task became fairly easy:
<TagPicker onResolveSuggestions={this.onResolveSuggestions}
..
inputProps={{
onBlur: () =>
console.log("onBlur called"),
onFocus: () =>
console.log("onFocus called"),
"aria-label": "Tag Picker",
onKeyPress: (e) =>
{
var charInput = e.charCode;
// no modifier key and no lowercase
if(!e.ctrlKey && !e.metaKey && !e.altKey &&
!(charInput >= 97 && charInput <= 122)) {
//UPPERCASE => lowercase
if((charInput >= 65) && (charInput <= 90)){
charInput=charInput+32;
}
//UNDERSCORE => dash
if((charInput == 95)){
//DASH
charInput=45;
}
if((charInput >= 97 && charInput <= 122) || charInput == 45) {
const start = e.currentTarget.selectionStart;
const end = e.currentTarget.selectionEnd;
const isPrevCharDash = (start > 0 && e.currentTarget.value.charAt(start-1) === "-");
if(!((start == 0 || isPrevCharDash) && charInput == 45)){
e.currentTarget.value = e.currentTarget.value.substring(0, start) + String.fromCharCode(charInput) + e.currentTarget.value.substring(end);
e.currentTarget.setSelectionRange(start+1, start+1);
}
}
e.preventDefault();
}
}
}}
/>
Here is a demo.