Skip to content

useStartTyping

Category
Export Size
1.06 kB
Last Changed
5 days ago

Fires when users start typing on non-editable elements. Useful for auto-focusing an input field when the user starts typing anywhere on the page.

Demo

Usage

tsx
import { 
useStartTyping
} from '@reause/core'
import {
useRef
} from 'react'
const
input
=
useRef
<HTMLInputElement>(null)
useStartTyping
(() => {
if (
input
.
current
!==
document
.
activeElement
)
input
.
current
?.
focus
()
}) // <input ref={input} type="text" placeholder="Start typing to focus">

Custom Valid Key

ts
import { 
useStartTyping
} from '@reause/core'
useStartTyping
(handleKey, {
// only allow numbers
isTypedCharValid
:
e
=> /^\d$/.
test
(
e
.
key
),
})

Custom Editable Element

ts
import { 
isFocusedElementEditable
as
defaultEditable
,
useStartTyping
} from '@reause/core'
useStartTyping
(handleKey, {
isFocusedElementEditable
: () => {
const {
activeElement
} =
document
// Exclude elements with id 'targetInput' if (
activeElement
?.
id
=== 'targetInput')
return true return
defaultEditable
()
}, })

How It Works

The callback only fires when:

  • No editable element (<input>, <textarea>, or contenteditable) is focused
  • The pressed key is alphanumeric (A-Z, 0-9)
  • No modifier keys (Ctrl, Alt, Meta) are held

This allows users to start typing anywhere on the page without accidentally triggering the callback when using keyboard shortcuts or interacting with form fields.

Both isFocusedElementEditable and isTypedCharValid are also exported as utility functions, so you can reuse them when writing custom options.

Type Declarations

ts
export interface UseStartTypingOptions {
    document?: Document;
    isTypedCharValid?: (event: KeyboardEvent) => boolean;
    isFocusedElementEditable?: () => boolean;
}

export function isFocusedElementEditable(): boolean

export function isTypedCharValid({ keyCode, metaKey, ctrlKey, altKey, }: KeyboardEvent): boolean

export function useStartTyping(callback: (event: KeyboardEvent) => void, options?: UseStartTypingOptions): () => void

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.7 on
a82a7 - fix(core): resolve DOM ref targets after commit
v0.1.0 on
6c362 - fix(core): resolve useStartTyping audit findings (#643)
29251 - feat(core): add useStartTyping (#35)

Released under the MIT License. v0.1.8