Skip to content

Commit

Permalink
feat: focus on multiselect when validation error occur
Browse files Browse the repository at this point in the history
  • Loading branch information
valeriocomo committed Dec 16, 2024
1 parent 6957ada commit 028f2b4
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions src/app/components/EditorMultiselect.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import { get } from "lodash";
import { useEffect, useRef } from "react";
import {
FieldPathByValue,
useController,
useFormContext,
} from "react-hook-form";
import { RequiredDeep } from "type-fest";
import PublicCode, { PublicCodeWithDeprecatedFields } from "../contents/publiccode";
import { useTranslation } from "react-i18next";
import { Multiselect } from "react-widgets";
import { Filter } from "react-widgets/Filter";
import { get } from "lodash";
import { RequiredDeep } from "type-fest";
import PublicCode, { PublicCodeWithDeprecatedFields } from "../contents/publiccode";
import flattenObject from "../flatten-object-to-record";

type Props<T> = {
fieldName: T;
Expand Down Expand Up @@ -37,6 +39,19 @@ export default function EditorMultiselect<
const description = t(`publiccodeyml.${fieldName}.description`);
const errorMessage = get(errors, `${fieldName}.message`);

const inputRef = useRef<HTMLInputElement>(null);

useEffect(() => {
const errorsRecord = flattenObject(errors as Record<string, { type: string; message: string }>);
const formFieldKeys = Object.keys(errorsRecord);
const isFirstError = formFieldKeys && formFieldKeys.length && formFieldKeys[0] === fieldName

if (isFirstError) {
inputRef.current?.focus()
}

}, [errors, fieldName, inputRef])

return (
<div className="form-group">
<label className="active" htmlFor={fieldName}>
Expand All @@ -51,6 +66,7 @@ export default function EditorMultiselect<
dataKey="value"
textField="text"
filter={filter}
ref={inputRef}
/>

<small className="form-text">{description}</small>
Expand Down

0 comments on commit 028f2b4

Please sign in to comment.