Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

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

HTML

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

CSS

tabletd {
  border: 1px solid red;
}

React Code

classDungeonextendsReact.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><tabletabIndex="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'));

Solution 2:

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

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

Post a Comment for "Onkeypress Event Not Called In Reactjs Render()"