useKeyboard
Handles keyboard interactions for a focusable element.
install | yarn add @react-aria/interactions |
---|---|
version | 3.7.0 |
usage | import {useKeyboard} from '@react-aria/interactions' |
API#
useKeyboard(
(props: KeyboardProps
)): KeyboardResult
Features#
useKeyboard
handles keyboard interactions. The only difference from DOM events is that propagation
is stopped by default if there is an event handler, unless event.continuePropagation()
is called.
This provides better modularity by default, so that a parent component doesn't respond to an event
that a child already handled. If the child doesn't handle the event (e.g. it was for an unknown key),
it can call event.continuePropagation()
to allow parents to handle the event.
Usage#
useKeyboard
returns props that you should spread onto the target element:
Name | Type | Description |
keyboardProps | HTMLAttributes<HTMLElement> | Props to spread onto the target element. |
useKeyboard
supports the following event handlers:
Name | Type | Description |
onKeyDown | (
(e: KeyboardEvent
)) => void | Handler that is called when a key is pressed. |
onKeyUp | (
(e: KeyboardEvent
)) => void | Handler that is called when a key is released. |
Example#
This example shows a simple input element that handles keyboard events with useKeyboard
and logs them to a list below.
NOTE: for more advanced text field functionality, see useTextField.
function Example() {
let [events setEvents] = ReactuseState([]);
let {keyboardProps} = useKeyboard({
onKeyDown: (e) => setEvents((events) => [`key down: ` ...events])
onKeyUp: (e) => setEvents((events) => [`key up: ` ...events])
});
return (
<>
<input ...keyboardProps aria-label="Example" placeholder="Type here" />
<ul
style={
height: 100
overflow: 'auto'
border: '1px solid gray'
width: 200
}>
eventsmap((e i) => (
<li key= i> e</li>
))
</ul>
</>
);
}
function Example() {
let [events setEvents] = ReactuseState([]);
let {keyboardProps} = useKeyboard({
onKeyDown: (e) =>
setEvents((events) => [
`key down: `
...events
])
onKeyUp: (e) =>
setEvents((events) => [`key up: ` ...events])
});
return (
<>
<input
...keyboardProps
aria-label="Example"
placeholder="Type here"
/>
<ul
style={
height: 100
overflow: 'auto'
border: '1px solid gray'
width: 200
}>
eventsmap((e i) => (
<li key= i> e</li>
))
</ul>
</>
);
}
function Example() {
let [
events
setEvents
] = ReactuseState([]);
let {
keyboardProps
} = useKeyboard({
onKeyDown: (e) =>
setEvents(
(events) => [
`key down: `
...events
]
)
onKeyUp: (e) =>
setEvents(
(events) => [
`key up: `
...events
]
)
});
return (
<>
<input
...keyboardProps
aria-label="Example"
placeholder="Type here"
/>
<ul
style={
height: 100
overflow:
'auto'
border:
'1px solid gray'
width: 200
}>
eventsmap(
(e i) => (
<li key= i>
e
</li>
)
)
</ul>
</>
);
}