Simpleton Simpleton - 1 month ago 9
Javascript Question

React not responding to key down event

I'm trying to implement some very basic key press detection and I can't get it to work at all. I have a bare component that should be picking up on the

onKeyDown
event but nothing gets logged out in the console:

class App extends React.Component {
constructor(props) {
super(props);
}

handleKeyDown(event) {
console.log('handling a key press');
}

render() {
return (
<ChildComponent onKeyDown={this.handleKeyDown} />
);
}
}

React.render(<App />, document.getElementById('app'));

Answer

The problem is that ChildComponent is not a component but a component factory. It will be replaced with the result of rendering the element created with that factory.

Insert the ChildComponent in a div and attach any event listener to the div, not ChildComponent. Replace <div> with <span> if you need inline display.

let {Component} = React;

class ChildComponent extends Component {
  render() {
    return ( <child-component>click me</child-component> );
  }
}

class App extends Component {
  handleClick(event) {
    console.log('handling a key press');
  }

  render() {
    return ( <div onClick={this.handleClick}><ChildComponent  /></div> );
  }
}

React.render(<App />, document.getElementById('app'));

See it in action on codepen