isFocusVisible is not set on elements using react-hook-form
Provide a general summary of the issue here
When I use react-hook-form I cannot focus WITH isFocusVisible on the Select element.
The Select element itself gets the focus but without the isFocusVisible I cannot render a propper ring around the select.
https://github.com/user-attachments/assets/eed2395a-abfa-4ac5-ab0b-29cd4c0e3e0b
NOTE: I do understand that the components exposes a isFocused property that i could use to render the outline but that also means that after I select an element the outline will still be visible which is unwanted behavior.
🤔 Expected Behavior?
Once focus is set on the component via react-hook-form it should add the isFocusVisible property to it so the outline is shown.
😯 Current Behavior
No isFocusVisible gets set for Select, RadioGroup, CheckboxGroup etc...
💁 Possible Solution
No response
🔦 Context
No response
🖥️ Steps to Reproduce
https://github.com/zommerberg/react-aria-hook-form-bug
Version
"react-aria-components": "^1.3.1",
What browsers are you seeing the problem on?
Firefox, Chrome, Safari, Microsoft Edge
If other, please specify.
No response
What operating system are you using?
Windows 11
🧢 Your Company/Team
No response
🕷 Tracking Issue
No response
This is a bit tricky, we handle this in our own native form validation via https://github.com/adobe/react-spectrum/blob/main/packages/%40react-aria/form/src/useFormValidation.ts#L67. We have to set keyboard modality manually here since we don't want to set isFocusVisible=true for all programmatic focus movements (see https://react-spectrum.adobe.com/blog/building-a-button-part-3.html#focus-rings for a break down of some of the scenarios). However, since react-hook-form is handling the validation, that code path doesn't happen, so ideally there would be some way to have react-hook-form set keyboard modality here. I guess you could do something like
const onInvalid = () => {
setInteractionModality('keyboard');
}
...
<Form onSubmit={handleSubmit(onSubmit, onInvalid)}
but setInteractionModality comes from @react-aria/interactions directly and isn't exported from the mono repo. Not sure if we could handle this case automatically on our end
setInteractionModality("keyboard"); Does the trick for me. I made my own reusable useReactAriaHook form that will always call it on error.
import {
useForm,
UseFormProps,
UseFormReturn,
FieldValues,
UseFormHandleSubmit,
} from "react-hook-form";
import { setInteractionModality } from "@react-aria/interactions";
export function useReactAriaForm<
TFieldValues extends FieldValues = FieldValues,
TContext = any
>(
props?: UseFormProps<TFieldValues, TContext>
): UseFormReturn<TFieldValues, TContext> {
const form = useForm<TFieldValues, TContext>(props);
const enhancedHandleSubmit: UseFormHandleSubmit<TFieldValues> = (
onValid,
onInvalid
) => {
return form.handleSubmit(onValid, (errors, event) => {
setInteractionModality("keyboard");
if (onInvalid) {
onInvalid(errors, event);
}
});
};
return {
...form,
handleSubmit: enhancedHandleSubmit,
};
}
Which then allows me to use it like this:
@LFDanLu Do you think it is a good idea to update the react-hook-form documentation with that example?
Glad it works for you! Documentation would definitely be nice, but I'm a bit wary about exposing setInteractionModality since it really isn't supposed to be public api. Lemme chat with the team about if there are any alternatives or if we need to setup a helper of sorts rather than exposing that setter directly.
Sorry about the delay, the team discussed this and we'll want to make a helper utility for this (the helper utility would handle setting the keyboard modality and possibly allow a user to specify a element to focus as well). For now it would be best not to use setInteractionModality directly if possible because it isn't public api, could you try dispatching a keyboard event instead to trigger keyboard modality?
Any additional information on what type utility that you would want for this? This seems to be a blocker for our users because it prevents integration with react-hook-form. Just curious if there is any way that I could be of help.
@LFDanLu if you recall more, but I don't think we had a good idea yet. The general shape was, something named more appropriately to help with a case like react-hook-form, maybe moveVisibleFocus / showFocusIndicator / visiblyFocus or something like that, because it's not obvious that changing the interaction modality will result in focus suddenly being visible.
I think once we start a review we'll have some more ideas, but hopefully that's enough to get it started. Thank you!
that about sums up what I remember from our original discussion
@LFDanLu @snowystinger So it seems like the general idea is just to create some sort of wrapper around setInteractionModality? I see that pretty much everything else coming from @react-aria/interactions is a hook, so would you prefer that this be a hook that is exported from the parent react-aria package?
As a temporary workaround and based on the feedback above from @LFDanLu, I created a small utility to replace the internal utility in that custom hook, which seems to work currently.
export function synthesizeKeyboardModality(key: string = "Tab"): void {
try {
const ev = new KeyboardEvent("keydown", {
key,
bubbles: true,
cancelable: true,
});
document.dispatchEvent(ev);
window.dispatchEvent(ev);
} catch {
// Fallback for older browsers
const ev = new Event("keydown", { bubbles: true, cancelable: true });
document.dispatchEvent(ev);
window.dispatchEvent(ev);
}
}
Lets start with a hook to match the others for now.
Hi — I’d like to work on this if the public hook contract aligns with the team’s direction. I reviewed the discussion and closed #9662. My proposed hook would expose a narrow “make this validation-driven programmatic focus visibly focused” operation without exporting setInteractionModality. It could optionally accept a target/ref and use the existing safe-focus path, while ordinary programmatic focus and pointer-driven focus would remain unchanged. Tests would cover an already-focused invalid field, optional target focusing, pointer/programmatic negative cases, and a React Aria Components form-validation integration; I’d also add the react-hook-form example and Storybook coverage. Is useFocusVisibleTrigger the intended name, and should target focusing be part of the first version or should v1 only affect the currently focused element?
I am not sure what all that says. It should be pretty straightforward:
function useShowFocusIndicator() {
return () => setInteractionModality(true);
}
let showFocus = useShowFocusIndicator();
showFocus();
Tests are much appreciated. We don't have react-hook-form currently installed anywhere, it might be better to determine what about the library was causing it to not work (might've been mentioned above), then simulate that in the test, rather than installing the library.
Thanks for the clarification. I kept this to the thin hook plus focused behavior test and opened draft PR #10426: https://github.com/adobe/react-spectrum/pull/10426