Skip to content

Instantly share code, notes, and snippets.

@HynekS
Last active October 4, 2020 16:32
Show Gist options
  • Save HynekS/a142431475b7e8ce47f6b2f445f43983 to your computer and use it in GitHub Desktop.
Save HynekS/a142431475b7e8ce47f6b2f445f43983 to your computer and use it in GitHub Desktop.
import { useEffect, useRef } from "react"
export default function useFocusNextOnEnter() {
const formRef = useRef()
const isForm = node => Boolean(node.nodeName === "FORM")
const handleKeyPress = e => {
if (e.key === "Enter" || e.keyCode === 13) {
const form = e.target.form
const index = [].indexOf.call(form, e.target)
if (form.elements[index + 1] && form.elements[index + 1].getAttribute("type") !== "submit") {
form.elements[index + 1].focus()
e.preventDefault()
}
}
}
useEffect(() => {
if (formRef.current && isForm(formRef.current)) {
formRef.current.addEventListener("keypress", handleKeyPress)
return formRef.current.removeEventListener("keyPress", handleKeyPress)
}
console.error("Invalid call: Component using 'useFocusNextOnEnter' hook must be a form element")
}, [])
return formRef
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment