'How to use react-hotkeys-hook to submit a form with react-hook-form
I want to submit a form with react-hook-form using the useHotKeys from react-hotkeys-hook
I have attached a code sandbox trying this. I want to submit a form when a hotkey is clicked as well as when the submit button is clicked. Can this be done?
https://codesandbox.io/s/react-hoot-form-usehotkeys-009rk?file=/src/App.js
Solution 1:[1]
My form uses material-ui-confirm to conditionally confirm submissions, but when I added the option to submit it by using hotkeys, using handleSubmit(onSubmit)(), that confirmation would be ignored.
I did this workaround and it seems to be working, though:
// had to extract confirmation logic to a function
const confirmSub = async (data: any) => {
if (!conditions) {
await confirm({
title: "Message",
description: "Desc",
});
}
};
// fire submission when the user presses ctrl+enter on a textarea
// notice how onSubmit() is called
useHotkeys(
"ctrl+enter",
() => {
handleSubmit(async (data) => {
await confirmSub(data);
await onSubmit(data);
})();
},
{
enableOnTags: ["TEXTAREA"],
},
);
const onSubmit = async (data: any) => {
// have to keep this in case the user uses a button to submit
await confirmSub(data);
await mutation.mutate(data);
};
// define mutations and rest of the code below
Maybe the same logic can be applied to validation, since this way you have access to the data object before handleSubmit is fired?
A but convoluted, but that's all I got for now.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 18_ |
