DEV Community

Cover image for React Forms focus next field on enter
Marinko
Marinko

Posted on

React Forms focus next field on enter

Hi everyone,
This is my first post on dev.to
I started to learn react few months ago and i'm starting to get comfortable with it.

On my project I had an idea to use enter key to go to the next field in the form that is focusable (mimic tab functionality). I didn't want to use useRef on each field and manually adjust focus because it would be cumbersome.

Hook is called "useFocusOnEnter".

const useFocusOnEnter = (formRef) => {
    const onEnterKey = (event) => {

        if (event && event.keyCode && event.keyCode === 13 && event.target && event.target.form) {
            const form = event.target.form;
            const index = Array.prototype.indexOf.call(form, event.target);
            for (let i = index + 1; i < formRef.current.length; i++) {
                if (formRef.current[i].tabIndex === -1) {
                    continue
                }
                formRef.current[i].focus();
                if (document.activeElement === formRef.current[i]) {
                    break;
                }
            }
        }
    }

    return {onEnterKey};
}

export default useFocusOnEnter;

Enter fullscreen mode Exit fullscreen mode

And to see it in action:

const FormComponent = ({stavka}) => {

    const form = useRef();
    const {onEnterKey} = useFocusOnEnter(form);

    const handleSubmit = (e) => {
        //handle submit
    }

    return (
        <form ref={form} onKeyUp={event => onEnterKey(event)}>
            <input autoFocus/>
            <input />
            <input />
            <input />
            <input />
            <button type="button" onClick={handleSubmit}>Save</button>
        </form>
    );
}
export default FormComponent;
Enter fullscreen mode Exit fullscreen mode

Thank you for reading

Top comments (0)