Zolbayar
Zolbayar

Reputation: 936

onKeyPress event not called in ReactJS render()

I' trying to listen for keyboard events in ReactJS like this:

class Dungeon extends React.Component {

  onKeyPress(e){
    console.log(e.charCode); 
  }

  render(){
    var rows = [];
    for (var i=0; i < boardHeight; i++) {
        rows.push(<DungeonRow rowId={i} />);
    }

    return (
      <table onKeyPress={this.onKeyPress}>
        {rows}
      </table>
    ); 
  }
}

But the onKeyPress is not called when I click on the keyboard. What went wrong?

Upvotes: 2

Views: 3233

Answers (2)

Yash Sharma
Yash Sharma

Reputation: 830

Did you bind your function ?
If not change the definition to

onKeyPress=(e)=>{
   console.log(e.charCode); 
}

Upvotes: 0

Pablo Darde
Pablo Darde

Reputation: 6432

You can use JSX "onKeyDown" to detect key codes:

https://jsfiddle.net/pablodarde/bg8sek2r/

HTML

<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

CSS

table td {
  border: 1px solid red;
}

React Code

class Dungeon extends React.Component {
  constructor(props) {
    super(props);
    this.inputListener = this.inputListener.bind(this);
  }

  inputListener(event) {
    const key = event.keyCode;
    if (key === 40) {
        alert("Arrow down pressed!");
    }
    }

    render() {
        return(
        <div>
        <ol>
          <li>Click in this area</li>
          <li>Press TAB to select the table</li>
          <li>Press ARROW DOWN</li>
        </ol>
          <table tabIndex="0" onKeyDown={this.inputListener} ref={(elem) => { this.tbl = elem; }}>
          <tr>
            <td>column A</td>
            <td>column B</td>
          </tr>
        </table>
        </div>
     )
   }        
}

React.render(<Dungeon />, document.getElementById('container'));

Upvotes: 4

Related Questions