Last active
October 4, 2020 16:32
-
-
Save HynekS/a142431475b7e8ce47f6b2f445f43983 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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