Skip to content

Commit 956d443

Browse files
committed
Additional example
1 parent 2b913db commit 956d443

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

README.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,47 @@ const handleSubmit = (e) => {
150150
</form>;
151151
```
152152
153+
Your explanation about using `isValid` and `isDirty` for conditional rendering in forms is clear and informative. Here's an improved version with some extensions and code refinement:
154+
155+
---
156+
157+
### Using `isValid` and `isDirty` for Conditional Rendering in Forms
158+
159+
In some scenarios, it's useful to conditionally render elements based on the form's validity or whether the form has been interacted with (i.e., is "dirty"). While disabling the submit button for an invalid form is generally not recommended due to accessibility concerns, there are other ways to provide feedback to the user.
160+
161+
For example, product managers often require displaying error messages below a form, particularly in long forms, to inform users about any issues after submission.
162+
163+
Here’s how you can implement this in a long form scenario:
164+
165+
```jsx
166+
<form onSubmit={handleSubmit}>
167+
<input
168+
type="text"
169+
value={form.state.title.value}
170+
onBlur={() => form.onBlur('title')}
171+
/>
172+
<span>{form.state.title.error}</span>
173+
<button type="submit">Save</button>
174+
</form>;
175+
176+
{
177+
!form.isValid && (
178+
<div>
179+
{Object.keys(form.state).map((inputName) => {
180+
const error = form.state[inputName].error;
181+
return error ? (
182+
<div key={inputName}>
183+
{inputName}: {error}
184+
</div>
185+
) : null;
186+
})}
187+
</div>
188+
);
189+
}
190+
```
191+
192+
In this example, if the form is invalid (`!form.isValid`), we loop through the `form.state` object and render each error message. Each error message is associated with its corresponding field name for clarity. This approach helps in guiding users to correct their inputs, especially in long forms where errors might not be immediately visible.
193+
153194
### Exports from useAJVForm
154195
155196
The `useAJVForm` hook provides a set of utilities and state indicators for robust form management and validation. Below is a detailed description of each export from the hook:

0 commit comments

Comments
 (0)