Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 838
Daniel May Avatar asked Mar 09 '16 09:03

Daniel May


2 Answers

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 ;).

like image 155
Eliecer Chicott Avatar answered Nov 09 '22 00:11

Eliecer Chicott


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});  
}
like image 29
gyzerok Avatar answered Nov 08 '22 23:11

gyzerok