0

I'm working on a little editor in react but in textarea I don't want the tab button to switch to the next field.

I tried a few variations of

<textarea className={style.textarea}
    required
    tabIndex="-1"
    type="text"
    value={text}
    onChange={(e) => setText(e.target.value)}
/>

without any luck. For example, I used tabindex="-1" as well without any luck. For example, I used tabIndex="-1" as using an integer -1` but that also didn't work.

The desired behavior is that when I press Tab that it'd put a literal tab in my textarea instead of switching focus.

Pratap Alok Raj
  • 1,098
  • 10
  • 19
financial_physician
  • 1,672
  • 1
  • 14
  • 34

2 Answers2

0

It looks like onchange won't be effective for this as it only fires when focus leaves the textarea. Additionally onkeyup wouldn't be a great solve here because for accessibility reasons you want to allow users to tab into the textarea but then have tab perform a different function when focus is inside it.

Something like this may do the trick:

function handleKeyDown(e) {
  if (e.key == "Tab") {
    e.preventDefault();

    const start = this.selectionStart;
    const end = this.selectionEnd;

    this.value =
      this.value.substring(0, start) + "\t" + this.value.substring(end);

    this.selectionStart = this.selectionEnd = start + 1;
  }
}
<form>
  <textarea onkeydown="handleKeyDown.call(this, event)"></textarea>
</form>
Ross Moody
  • 773
  • 3
  • 16
0
  1. tabIndex accepts number as a parameter. In react, the correct way to pass in a number to an attribute is by wrapping it in curly braces { }. This is how you should do this.
  2. attribute type does not exist on textarea

<textarea className={style.textarea}
    required
    tabIndex={-1}
    value={text}
    onChange={(e) => setText(e.target.value)}
/>

Ashutosh kumar
  • 570
  • 6
  • 13