Reputation: 15246
I have a MUI TextField
that is defined as multi-line. My goal is to enter JSON text. I found that when I pressed the tab key, my component lost focus and focus was given to the next component on screen. What I desire is to have the tab value (\t) entered into the string text. Is there a recipe to disable the tab key as a navigation tool?
Upvotes: 3
Views: 2073
Reputation: 81290
By default, if you press Tab in the input
field, the browser will switch focus to the next element. To override that behavior, you can listen to the keydown
event and call e.preventDefault()
, then add some code to insert the tab character at the cursor position. Below is the implementation. Note that because you are tampering with the input value
, the undo feature doesn't work anymore:
<TextField
multiline
onKeyDown={(e) => {
const { value } = e.target;
if (e.key === 'Tab') {
e.preventDefault();
const cursorPosition = e.target.selectionStart;
const cursorEndPosition = e.target.selectionEnd;
const tab = '\t';
e.target.value =
value.substring(0, cursorPosition) +
tab +
value.substring(cursorEndPosition);
// if you modify the value programmatically, the cursor is moved
// to the end of the value, we need to reset it to the correct
// position again
e.target.selectionStart = cursorPosition + 1;
e.target.selectionEnd = cursorPosition + 1;
}
}}
/>
Upvotes: 5