Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
31
rated 0 times [  37] [ 6]  / answers: 1 / hits: 24946  / 9 Years ago, thu, august 27, 2015, 12:00:00

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

More From » reactjs

 Answers
47

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>press down a key</child-component> );
}
}

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

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

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

See it in action on codepen


[#65271] Tuesday, August 25, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austynp

Total Points: 505
Total Questions: 118
Total Answers: 106

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
austynp questions
;