0

In our application a form is no trivial, as the form is build based on data from the server and not a flat structure.

Still, the elements are placed (eventually) sequentially, and I'd like to have something happen when tab is pressed in the last element of said form.

The form would look like:

function (props) {
    const {elementTree} = props;
    function onLastElemTabbed(e) {
       console.log("something magical happens")
    }

    return <form>
        <ComponentRenderer elementTree={elementTree}/>
    </form>
}

function ComponentRenderer(props) {
    const {elementTree} = props;
    return <>
        elementTree.map((elem, idx) => {
            if (elem.type === 'input') {
                return <input/>;
            } else if (elem.type === 'fieldset') {
                return <fieldset>
                    <ComponentRenderer elementTree={elem.subGroup}/>
                </fieldset>
            }
        }
    </>
}

I could always pass the function into the ComponentRenderer, but that feels really dirty as it's just passing props down (in another similar form the same renderer is used however there tab on last element press is not important).

Is there a way similar to form's onSubmit function to notice the user has finished all fields?

paul23
  • 8,799
  • 12
  • 66
  • 149
  • Do you specifically need an event handler for Tab key pressed from the last input text field, or would it suffice to know if all fields are filled out, allowing the form to be submittable? I'm assuming you are interested in the later, perhaps to enable the submit button only when all fields have been filled? – Chunky Chunk May 24 '20 at 16:33
  • Nah it's actually a tab (or enter for that matter) that I"m interested in. This *particular* form-tree consists of a list of "accounts", and tabbing at the last farm should add a new element. (For brevity I've left that gruntwork for that at home, basically it's a layer between the form and `ComponentRenderer`). – paul23 May 24 '20 at 17:16
  • if you look at my answer it will show you how to listen for any key event. https://stackoverflow.com/questions/33211672/how-to-submit-a-form-using-enter-key-in-react-js/59148029#59148029 – Cyrus Zei May 25 '20 at 04:46
  • @CyrusZei thanks, but that would require to pass the event handler down to, and through, any containing code. Which would litter the components with details that are not important to the component itself. Especially the fact that intermediate components also need to pass it down feels irky. – paul23 May 25 '20 at 22:51

0 Answers0