glortho / react-keydown Goto Github PK
View Code? Open in Web Editor NEWLightweight keydown wrapper for React components
Home Page: http://glortho.github.io/react-keydown/example/index.html
License: MIT License
Lightweight keydown wrapper for React components
Home Page: http://glortho.github.io/react-keydown/example/index.html
License: MIT License
Functions
@keydown('shift+enter', 'ctrl+enter', 'alt+enter')
handleInputKeydown(e) {
console.log('next line');
}
@keydown('enter')
handleSubmit(e) {
console.log('submit');
}
Text Area
<textarea
name="content"
placeholder={placeholderText}
value={this.state.content}
onChange={this.handleInputChange}
onKeyDown={(e) => { this.handleInputKeydown(e); this.handleSubmit(e) }} />
Did the above instead of just one function since I couldn't find a way to discern between a regular Enter key and Shift+Enter. The event prop in the function just gives you one key (last pressed I assume), so I separated them into 2 functions.
It's working fine, however, the function seems to be called twice. When I hit enter, I see 'submit' in the console twice.
While using this great lib, I felt the need to have debounce support. I'd be happy to PR it if guys here think its fine to implement as part of this.
Hi admin,
I just add react-keydown, and using Class Decorator, but the error occur at character "@" ,
Please help me.
p/s: copy all source from demo: http://glortho.github.io/react-keydown/example/index.html
Thanks
dist/store.js contains Array.from uses, which is not support by IE11.
Thanks!
I've got a situation I have first check some conditions, and if not met, let the event go upstream. Is that possible?
How do you handle shift+enter here?
@keydown('enter', 'shift+enter')
handleKeyDown({ keyCode }) {
if (keyCode == SHIFT_ENTER) {
// add a line break
} else {
// submit
}
}
My users (mostly children) sometimes hold the key down (on purpose or because they can't lift their hand off the switch because of disability) thus triggering key repeat. I typically avoid this by binding keyup to clear a flag set on keydown and ignoring the keydown event if the flag is set.
I don't see that in your package but it looks like it would be simple to add. If you agree, I may try hacking it to produce a pull request.
Hi, I'm trying to set up a textfield to, on enter, submit. But to support adding newlines, add a keybinding for ctrl + enter. Capturing ctrl+enter is simple using
`
@keydown('ctrl+enter', 'enter')
onKeyDown({ keyCode, ctrlKey }) {
}
render() {
return (
);
}
`
But, capturing just the simple 'enter' press, does not work. Instead it gets handled, I assume by the Textfield itself. What is the best way to approach this?
https://webpack.js.org/guides/tree-shaking/
For example, if you only use method decorators, it won't include the class decorator code (as long as you use ES6 export syntax and none of the modules are running functions that might have side-effects).
Here's how redux-form does it: https://github.com/erikras/redux-form/blob/master/package.json#L15
react-keydown is kinda biggish when bundled, and on mobile, every KB counts to improve initial interaction.
I'm new to react so I could be doing something wrong. I'm trying to use the method decorator pattern which seems pretty straight forward, but my method is never firing. I stepped through some of your project code and from what I can tell in method_decorator.js (dist version) line 35, "var componentDidMount = target.componentDidMount;" is receiving undefined.
I realize this isn't much info, what can I do to debug this issue?
Options could be:
Refocus on previous if it is parent of current unmounting instance
Auto focus on previous no matter what when current unmounts.
Etc.
<MyComp1 having keydown>
<1>
.
.
<n> having keydown scoped </n>
.
.
</1>
</MyComp>
In this scenario keydown is not working
Hi, can I watch only ctrl click?
I tried this:
@keydown(17)
class Test extends Component{
}
But, if I am not wrong, matchKeys
waits modifier + key
when i press ?, the keydown is not working
Let's say I have a list of items that I am rendering on a page. Each item is a component. Inside that component I am listening for key events, but I only want to listen when that component has a prop passed in called isSelected.
As it stands now, all of those components in the list are listening and I want to prevent that.
The following handler should only fire when this.props.isSelected === true:
@keydown('up','down') handleKeyDown(e){ console.log('handleKeyDown', e); e.preventDefault(); }
The class decorator, for example, is less obtrusive when used on its own than the method decorators.
Matched only single esc, but not esc+any_key. Is it possible to implement?
I am having trouble installing react-keydown
via jspm, which converts version ranges down to ^
and ~
operators in an attempt to naturally enforce semver.
It seems that the the specified react-dom
range of >=^0.14.0
is not a valid range according to https://github.com/npm/node-semver and thus fails to install.
Could you please consider changing the react-dom
version range to ^0.14.0
to ensure compatibility with jspm?
Thanks in advance,
Max
I have a dropdown component which has the following
@keydown('esc')
closeOnEscape (ev) {
ev.preventDefault()
this.close()
}
and it seems that only the last one is ever called. Looks like its because of same handler passed to react-keydown and its only calling the last one.
Can anyone reproduce this issue?
Not all key codes have string equivalents in keys.js.
Thoughts on how to achieve this? Should it be baked into the library the same way as input and textarea?
I'm wondering if it's possible to capture events that aren't specifically sent to the component, but to still trigger a component's method.
My usecase is I have a grid in the center of the page, and I'm moving a little box around within it using the arrow keys. This works perfectly when the grid has "focus" by clicking on it, but I'd like for it to be able to capture keydown events on the window/document overall.
Not a huge problem if it's not possible, just thought I'd check if it is. This is an awesome library, super well-crafted =)
Currently it is working with Babel 5 decorators support, but something happens in babel-plugin-transform-decorators-legacy.
Using https://github.com/christianalfoni/webpack-express-boilerplate as a basis with babel-plugin-transform-decorators-legacy.
If an input field has focus in the component, the handler is not triggered.
I am using the decorator method.
The readme mentions that decorators are currently broken in Babel 6. Has anyone recently tried this library with the latest version of Babel?
NOTE: If react-keydown isn't working for you, be sure to check that you're not using Babel 6.x, as decorators are currently broken in Babel 6.
The link in that note (babel/babel#2645) is broken, and the Babel 6.0 release blog post mentions decorator support:
There are a couple of updated TC39 proposals that have come out. Babel 6 updates to the latest revisions of decorators, class properties, and others.
It seems like all you need to do is enable the stage 1 preset plugin to get decorator support.
Currently says import {...} from 'keydown'
. Should be import {...} from 'react-keydown'
Hi!
Since react 0.14.0 there is an error when I decorate a method in a react component with @keydown(key)
(react-keydown 1.3.6):
class_decorator.js:19 Uncaught TypeError: Cannot call a class as a function
Worked for me with react 0.14.0-rc1.
Array.prototype.fill is still not widely supported (e.g. no IE versions support it).
Is there any plan to update the module to accept React v15 as a dependency. I did this locally, by updating package.json, but curious if it was something you were planning on doing.
Thanks.
In the readme, the link to the github.io site give 404
See #55
To test our components and their interactive with react-keydown
we usually write tests which simulate events, like so:
const event = document.createEvent('Event');
event.initEvent('keydown', true, true);
event.keyCode = 27;
event.which = 27;
document.dispatchEvent(event);
This then allows us to run tests to ensure react-keydown
was bound correctly and fires the right callback.
However, after upgrading from 1.7.2
to 1.7.3
these tests are no longer working due to the changes in made here:
function _shouldConsider(_ref3) {
var ctrlKey = _ref3.ctrlKey,
target = _ref3.target;
return ctrlKey || !~['INPUT', 'SELECT', 'TEXTAREA'].indexOf(target.tagName) && target.getAttribute('role') !== 'textbox';
}
The issue is that this code assumes target.getAttribute
is a valid function, however, in a test environment the target will be the document
object which is created in jsdom
and which may not actually have getAttribute
defined.
Would it be possible to update react-keydown
to check for the existence of this function first? So the code would become:
return (
ctrlKey ||
!~['INPUT', 'SELECT', 'TEXTAREA'].indexOf(target.tagName) &&
// Make sure the event target supports `getAttribute`
target.getAttribute &&
target.getAttribute('role') !== 'textbox'
);
Without this, we've had to revise our tests to do this in the meantime:
const event = document.createEvent('Event');
event.initEvent('keydown', true, true);
event.keyCode = 27;
event.which = 27;
document.getAttribute = () => null; // Hacky Fix
document.dispatchEvent(event);
All the documentation for react-keydown
is using the legacy decorator feature of Babel. I'd like to move away from this Babel plugin but I can't figure out how to use react-keydown
without decorators. Everything I've tried seems to fail.
Can you please add some simple documentation about how to wrap classes and class methods without using decorators?
'react-keydon' uses symbol in lib/keys.js
method
export function allKeys( arg ) {
return arg ? typeof arg === 'symbol' : Symbol( 'allKeys' );
}
But this typechecking didn't work with symbol polyfill. I use polyfill because i need to support ie10+, Safari 7+ browsers.
Symbol
For support this you can use:
Babel plugin
The plugin generally works well for me as long as I use clicking to switch focus between components. But I'm making an app that is keyboard-only and would like to manually choose which component is currently active. For example:
I have tried calling .focus()
on the primary element of the component I'd like to focus, but it doesn't seem to do anything. Is there a way to do this?
Add a @keydown( 'right' );
Decorator to my function, it works on Chrome and Safari perfectly but on IE it doesnt do anything.
Is there a ways to debut it, for exaple get infrimations if the key event was triggered in the component when the key was pressed?
Is there any way to use react-keydown with a stateless component?
I know ES7 decorators are only supported with classes and not functions. Is there any workaround to this? Or do I have to switch to some other library? I really like react-keydown and would want to stick to it.
I recently tried to do:
@keydown('delete')
but it doesn't appear to be supported. Of course:
@keydown(46) // 46 == delete
does still work, but if it's not too much trouble could you please add an "alias" for delete?
In my use case, Iโd like to be able to toggle state based on if a modifier key is pressed, so it would be great to be able to do something like:
class MyComponent extends React.Component {
@keydown('alt')
setModeCopy(event) {
this.setState({ mode: 'copy' });
}
@keyup('alt')
setModeMove(event) {
this.setState({ mode: 'move' });
}
}
In actually use, I think I would use @keydownScoped and @keyupScoped.
react-keydown
has worked great for me in the browser, but when I try to use Enzyme to test it I can't figure out how to simulate a keydown event that react-keydown
will actually respond to.
If I have a component ...
class SomeComponent extends React.Component {
@keydown('ctrl+a')
handler() {
throw new Error(`Proof that we hit this line`);
}
}
and then I try to test it with Enzyme:
const A_KEY = 65;
const component = new SomeComponent();
component.simulate('keyDown', {ctrlKey: true, keyCode: A_KEY})
// an error should have been thrown here
no error ever gets thrown, indicating that the handler never got hit.
I tried looking through the source but wasn't able to figure out where exactly react-keydown
looks at the event and decides which handler to forward to, so any help either:
A) pointing me toward that place in the code
B) (ideally) providing an example of how to use Enzyme to test react-keydown
would be greatly appreciated.
EDIT
Two minor follow up issues (both related to testing react-keydown
-decorated methods directly instead of via simulate
)
If you use Node.js + JSDom to run your tests things will break because
ReferenceError: KeyboardEvent is not defined
That's easy enough to fix (global.KeyboardEvent = window.KeyboardEvent
), but if react-keydown
could just use window.KeyboardEvent
it would save users from a potential pain point.
@keydown
lose their return values. Obviously this doesn't matter normally, because event handlers don't normally return things, but it can be handy to have handlers return things for tests (eg. if the handler generates a promise, it can be handy for the test to get that promise back from the handler).A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.