Daniel May
Daniel May

Reputation: 2262

Prevent React from capturing tab character

I have an input field. I want React to check if a tab has been pressed in this field. If so, then process the contents of that field (e.g. ajax call).

getInitialState: function() {
  return { name: "" }; 
},

handleChangeName: function(e) {
  this.setState({name: e.target.value});
},

handleKeyUp: function(e) {
  if (e.keyCode == 9) {
    e.preventDefault();
    alert("Execute ajax call after tab pressed");
  }
},

<input type="text" value={this.state.name} onChange={this.handleChangeName}
   onKeyDown={this.handleKeyUp} />

Problem:

Tab keypress is intercepted and subsequent code executed but the tab character is inserted into the input text field. How do I prevent this from happening?

I have tried various combinations of preventDefault, stopPropagation, stopImmediatePropagation. I can get a result of no further chars being inserted into the input text field, but then no subsequent code is executed.

What am I missing?

Upvotes: 15

Views: 15322

Answers (2)

Eliecer Chicott
Eliecer Chicott

Reputation: 581

The events onKeyUp or onKeyPress won't be called when 'Tab' is pressed because it triggers a onBlur before, you need to catch it with onKeyDown. You can try to use the event key instead of keyCode, as the example above.

function:

 handleKeyDown: function(e) {
    if (e.key === "Tab") {
      e.preventDefault();
      alert("Execute ajax call after tab pressed");
    }
  }

input:

<input type="text" onKeyDown={this.handleKeyDown} />

I hope it helps ;).

Upvotes: 22

gyzerok
gyzerok

Reputation: 1418

I think it's somehow connected with the fact that you pass both onChange and onKeyDown handlers.

I think you have following options:

  1. Try to change order of these handlers: onKeyDown - first, onChange - second. I am not sure that would help.
<input type="text" value={this.state.name} onKeyDown={this.handleKeyUp} onChange={this.handleChangeName} />
  1. You can handle both cases in the single handler like onKeyDown or onKeyPress.
handleKeyPress(e) {
  if (e.keyCode === 9) {
    e.preventDefault();
    return alert('hey ho lets go');
  }

  this.setState({name: e.target.value});  
}

Upvotes: 3

Related Questions