Reputation: 1685
I have a Search component which has an input field inside. All elements inside it receive the onKeyDown event bubbling. However, when I use the component, it doesn't listen to the event. It's parent, however does.
In the example below, when I press a key inside the search field, it prints 'parent', but it doesn't print 'component'
<div className="xyz" onKeyDown={(e)=>console.log('parent')}>
<Search onKeyDown={(e)=>console.log('component')}/>
</div>
Is this expected behavior? Am I missing something? Here is a working fiddle https://jsfiddle.net/69z2wepo/80974/ to test, open the console, select the input and click any keyboard key.
Notice the console.log in the component declaration never fires, but it's parent does.
Upvotes: 4
Views: 1463
Reputation: 10227
When you write <Search onKeyDown={(e)=>console.log('component')}/>
you don't set onKeyDown
event listener on Search
component. You are actually passing onKeyDown
property to the component. So then you can write in your Search
component:
return <div onKeyDown={this.props.onKeyDown}>
...
In DOM structure your Search
component is a <div>
element in which you wrap your <input>
. So if you want to set listener on Search
component, set it on <div>
-wrapper inside of it.
Virtual DOM persists the structure of the original DOM and checks for its changes (it just watches a view part of the DOM). It doesn't care about event listeners.
Here is a modified version of the fiddle, that does what you wanted: https://jsfiddle.net/69z2wepo/81069/
Upvotes: 2