Field focus tracking #1657
Replies: 3 comments 2 replies
-
I did some searches here on GitHub. I even asked Claude for an explanation, but I couldn't find a definitive answer. I was surprised because I would expect others to have this same question. |
Beta Was this translation helpful? Give feedback.
-
Here is a simplified email field showing what I have to do (red) for proper focus management versus what I'd like to have to do (green). My solution works, but it's not what I'd consider elegant. -// define a hook to abstract as much focus logic as possible while maintaining
-// form library functionality. obviously this is in a separate file
-const useFocusBlur = () => {
- const [isFocused, setIsFocused] = useState(false);
-
- return {
- isFocused,
- handleFocus: () => {
- setIsFocused(true);
- },
- makeHandleBlur: (field: AnyFieldApi) => () => {
- field.handleBlur();
- setIsFocused(false);
- }
- };
-};
-// set variable *per field*
-const emailFocus = useFocusBlur();
<form.Field name="email">
{(field) => (
<TextField
id="email"
label={t("name.label")}
- // ugly spread to include extra metadata versus clean meta=meta
- meta={{ ...field.state.meta, isFocused: emailFocus.isFocused }}
+ meta={field.state.meta}
name={field.name}
- // call wrapper function so focus can be be properly set. these
- // will be different for every field
- onFocus={emailFocus.handleFocus}
- onBlur={emailFocus.makeHandleBlur(field)}
+ onFocus={field.handleFocus}
+ onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
required
value={field.state.value}
/>
)}
</form.Field> I just don't understand why this is left for the user to deal with especially when |
Beta Was this translation helpful? Give feedback.
-
afaik form libraries usually does not have |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I only recently got started with the form library. Can someone help me understand why
onBlur
is handled butonFocus
is not? It seems obvious to includefield.handleFocus
sincefield.handleBlur
is already defined.What I really want though is
field.state.meta.isFocused
(or similar). What is the recommended approach to tracking field focus? I know I can manually manage it myself (awkwardly becausefield.handleBlur
still needs to be called), but that gets really tedious for more than a few fields.Beta Was this translation helpful? Give feedback.
All reactions