0

I want to capture keydown events from children. Is this possible? So say I have

onKeyDown = e => {
 e.stopPropagation();
 console.log("Hello world from Parent!");
 return false;
}

<ParentComponent onKeyDown={this.onKeyDown}>
  <div tabIndex='0' id='child'>Focus on me and press a button!</div>
</ParentComponent>

I want to print "Hello World" when you press a button while focused on the div child.

I've tried it and doesn't seem to be working, and reading another SO thread it seems to work with click handlers as long as e.stopPropagation() is used. How come it doesn't work with keydown events?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Pants
  • 2,563
  • 1
  • 20
  • 34

1 Answers1

2

I'm guessing you're not actually consuming the passed onKeyDown prop in the ParentComponent. You'd need to do something with it like so:

class ParentComponent extends Component {
  render(){
    return(
      <div onKeyDown={this.props.onKeyDown}>
        {this.props.children}
      </div>
    )
  }
};

See this working example

Per OP's questions in the comments below...

Stateless:

const ParentComponent = (props) => (
  <div onKeyDown={props.onKeyDown}>{props.children}</div>
)

In a div:

const ParentComponent = (props) => (
  <div>
    <div onKeyDown={props.onKeyDown}>{props.children}</div>
  </div>
)
Ted
  • 14,757
  • 2
  • 41
  • 58