diff --git a/packages/react-dom/src/events/SyntheticKeyboardEvent.js b/packages/react-dom/src/events/SyntheticKeyboardEvent.js index ef1ceedebe64e..2db2dd179303b 100644 --- a/packages/react-dom/src/events/SyntheticKeyboardEvent.js +++ b/packages/react-dom/src/events/SyntheticKeyboardEvent.js @@ -16,6 +16,12 @@ import getEventModifierState from './getEventModifierState'; */ const SyntheticKeyboardEvent = SyntheticUIEvent.extend({ key: getEventKey, + code: function(event) { + if (event.type === 'keydown' || event.type === 'keyup') { + return event.code; + } + return 0; + }, location: null, ctrlKey: null, shiftKey: null, diff --git a/packages/react-dom/src/events/__tests__/SyntheticKeyboardEvent-test.js b/packages/react-dom/src/events/__tests__/SyntheticKeyboardEvent-test.js index 06673f0fbe045..9426e58baeb9d 100644 --- a/packages/react-dom/src/events/__tests__/SyntheticKeyboardEvent-test.js +++ b/packages/react-dom/src/events/__tests__/SyntheticKeyboardEvent-test.js @@ -451,6 +451,52 @@ describe('SyntheticKeyboardEvent', () => { }); }); }); + + describe('code', () => { + it('returns code on `keydown`, `keyup` and 0 on `keypress`', () => { + let codeDown = null; + let codeUp = null; + let codePress = null; + const node = ReactDOM.render( + { + codeDown = e.code; + }} + onKeyUp={e => { + codeUp = e.code; + }} + onKeyPress={e => { + codePress = e.code; + }} + />, + container, + ); + node.dispatchEvent( + new KeyboardEvent('keydown', { + code: 'KeyQ', + bubbles: true, + cancelable: true, + }), + ); + node.dispatchEvent( + new KeyboardEvent('keyup', { + code: 'KeyQ', + bubbles: true, + cancelable: true, + }), + ); + node.dispatchEvent( + new KeyboardEvent('keypress', { + charCode: 81, + bubbles: true, + cancelable: true, + }), + ); + expect(codeDown).toBe('KeyQ'); + expect(codeUp).toBe('KeyQ'); + expect(codePress).toBe(0); + }); + }); }); describe('EventInterface', () => {