I have a component with an input element and I would like to trigger a "tab" keypress event on that input element in order to jump to the next input element whenever a certain set of logic happens.
I have a ref on the first input element and I'm attempting to trigger the keypress event like so:
useEffect(() => {
if (ref.current) {
ref.current.focus();
setTimeout(() => {
ref.current.dispatchEvent(
new KeyboardEvent("keypress", { key: "Tab" })
);
}, 3000);
}
});
First I make sure to select the first input element with .focus()
, then after 3 seconds I trigger pressing the tab key, expecting to see the focus move to the next field, but it does not seem to work.
It may seem like a strange example, but this is just a prototype. What I am actually planning to do is to trigger some code when I submit the first input field, that will fetch some rows with additional input fields and once that has been rendered I need to trigger the "tab" key. I would like to avoid attaching refs to these dynamically loaded input fields as I feel it adds a lot of overhead keeping track of the refs and passing them down, when all I need is to leverage the tab order and simulate a keypress to tab to the first dynamic loaded item once it has loaded. I'm ok with adding a single ref to the field you need to submit to populate the dynamic fields.
I noticed a few examples online calling .dispatchEvent()
directly on the ref object, but if I try that I get an error telling that the function does not exist, so I call it on the current
prop instead. Not sure if that has any relevance.
Here is a link to a prototype where the above code was taken from: https://codesandbox.io/s/wizardly-hopper-vrh4w?file=/src/App.js:149-441