Chapter 5 – Working with Forms

  1. In our generic Form implementation, why did we make the onSubmit function prop asynchronous?

The onSubmit function prop is likely to call a web service asynchronously and so needs to be asynchronous.

  1. When we implemented the generic Form and Field components, what was the purpose of the touched state?

The touched state allowed us to prevent validation checks when the user first enters the field, which can be annoying for the user. Generally, it is better to do the validation checks when the field loses focus and if the user comes back to the field and changes it.

  1. When we implement a form field like the following, why do we tie label to input using the htmlFor attribute?
<label htmlFor={name}>{label}</label>
<input
type="text"
id={name}
value={values[name] === undefined ? '' : values[name]}
onChange={handleChange}
onBlur={handleBlur}
/>

This makes the field accessible, which means a screen reader will read label when input gains focus. Clicking on label will also set focus to input.

  1. Why did we use the React context in our generic Form and Field implementations?

We used the React context to allow Field to access state such as the field value from Form. We couldn't pass the state via props because Form doesn't directly reference Fieldit indirectly references it via the children prop.

  1. Extend our generic Field component to include a number editor, using the native number input.

Here, we extend the type prop in Form:

interface Props {
name: string;
label?: string;
type?: "Text" | "TextArea" | "Password" | "Number";
}

In Form, JSX allows FieldInput to be rendered if type is Number:

{(type === "Text" || type === "Password" || type === "Number") && (
<FieldInput
type={type.toLowerCase()}
id={name}
value={values[name]}
onChange={handleChange}
onBlur={handleBlur}
/>
)}
  1. Implement a validator in Form.tsx that will check that the field value is between two numbers:
export const between: Validator = (
value: any,
bounds: { lower: number; upper: number }
): string =>
value && (value < bounds.lower || value > bounds.upper)
? `This must be between ${bounds.lower} and ${bounds.upper}`
: "";
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.110.17