The kind of a form where values for the fields controlled by the state
class MyForm extends PureComponent {
state = { pwd: "" };
render() {
return (
);
}
}
<input
type="password"
name="pwd"
id="pwd"
value={this.state.pwd}
onChange={this._handleChange}
/>
private _handleChange = (e: ChangeEvent<HTMLInputElement>) =>
this.setState({ pwd: e.target.value });
private _handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
console.log(`Form state`, this.state);
};
However, they are way less used
npm i react-hook-form
const MyForm: FC = () => {
return (
<form>
<h1>My form</h1>
<input type="password" />
<button>Submit</button>
</form>
);
};
const { register, handleSubmit } = useForm<{ pwd: string }>();
<input type="password" {...register("pwd")} />
const MyForm = () => {
const { register, handleSubmit } = useForm<FormData>();
const submit = (d) => console.log(d);
return (
<form onSubmit={handleSubmit(submit)} name="myform">
<h1>My form</h1>
<input type="password" {...register("pwd")} />
<p> <button>Submit</button> </p>
</form>
);
};
React-Form-Hooks make validation easy and customizable
const pwd = {
required: { value: true, message: "password required" }
minLength: { value: 6, message: "Too short!" }
};
<input type="text" {...register("pwd", pwd)} />
<div>{formState.errors?.pwd?.message}</div>
React-Form-Hook works only with Functional Components
Consider using React.memo when performance is crucial
Yup - platform agnostic javascript library for the declarative validation
import { BaseSchema, InferType, object, string } from "yup";
const validationSchema = object({
email: string().required().email(),
password: string().required().min(6).max(12),
});
const validations = useYup(validationSchema);
const { register, handleSubmit, formState } =
useForm<FormData>({resolver: validations});