Skip to content

Commit c4283ae

Browse files
authored
docs: Simplify focus-management example for invalid inputs (#1922)
Refactor onSubmitInvalid to focus on invalid input directly.
1 parent 9ce5f28 commit c4283ae

File tree

1 file changed

+8
-17
lines changed

1 file changed

+8
-17
lines changed

docs/framework/react/guides/focus-management.md

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -26,29 +26,17 @@ export default function App() {
2626
onSubmit() {
2727
alert('Submitted!')
2828
},
29-
onSubmitInvalid({ formApi }) {
30-
// This can be extracted to a function that takes the form ID and `formAPI` as arguments
31-
const errorMap = formApi.state.errorMap.onChange!
32-
const inputs = Array.from(
33-
// Must match the selector used in your form
34-
document.querySelectorAll('#myform input'),
35-
) as HTMLInputElement[]
29+
onSubmitInvalid() {
30+
const InvalidInput = document.querySelector(
31+
'[aria-invalid="true"]',
32+
) as HTMLInputElement
3633

37-
let firstInput: HTMLInputElement | undefined
38-
for (const input of inputs) {
39-
if (!!errorMap[input.name]) {
40-
firstInput = input
41-
break
42-
}
43-
}
44-
firstInput?.focus()
34+
InvalidInput?.focus()
4535
},
4636
})
4737

4838
return (
49-
// The `id` here is used to isolate the focus management from the rest of the page
5039
<form
51-
id="myform"
5240
onSubmit={(e) => {
5341
e.preventDefault()
5442
e.stopPropagation()
@@ -63,6 +51,9 @@ export default function App() {
6351
<input
6452
name={field.name}
6553
value={field.state.value}
54+
aria-invalid={
55+
!field.state.meta.isValid && field.state.meta.isTouched
56+
}
6657
onChange={(e) => field.handleChange(e.target.valueAsNumber)}
6758
type="number"
6859
/>

0 commit comments

Comments
 (0)