用material-ui TextField处理最新的react-hook-form错误 [英] latest react-hook-form error handling with material-ui TextField
问题描述
我很难,在材质UI中使用react-hook-form.
我准备了一个
I have difficulties, using react-hook-form with material-ui.
I prepared a codesandbox example.
import { TextField } from "@material-ui/core";
import React from "react";
import { useForm } from "react-hook-form";
import "./styles.css";
interface IMyForm {
vasarlo: string;
}
export default function App() {
const {
handleSubmit,
formState: { errors },
register
} = useForm<IMyForm>();
const onSubmit = (data: IMyForm) => {
alert(JSON.stringify(data));
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>First Name</label>
<TextField
variant="outlined"
margin="none"
label="Test"
{...register("vasarlo", {
required: "error text"
})}
error={errors?.vasarlo ? true : false}
helperText={errors?.vasarlo ? errors.vasarlo.message : null}
/>
<input type="submit" />
</form>
);
}
How can I properly use the register function, to get error message, write to input field, also the onSubmit
function to work?
I couldn't find answer in the documentation for this scenario.
In react-hook-form
v7, this is how you register an input:
<input {...register('name')} />
Calling register()
will return necessary props for your input like onChange
, onBlur
and ref
. These props make it possible for react-hook-form
to keep track of your form data. Now when you use register
with Material-UI TextField
like this:
<TextField {...register('name')} />
You pass the ref
property directly to the TextField
while the correct place to put it is in the inputRef
:
<TextField inputRef={ref} />
So you have to modify your code like this:
const { ref: inputRef, ...inputProps } = register("vasarlo", {
required: "error text"
});
<TextField inputRef={inputRef} {...inputProps} />
How can I properly use the register function, to get error message
There is nothing wrong with your error handling code. Though you can shorten you code a bit more using Typescript's optional chaining operator ?.
:
<TextField
error={!!errors.vasarlo}
helperText={errors?.vasarlo?.message}
inputRef={ref}
{...inputProps}
/>
Live Demo
这篇关于用material-ui TextField处理最新的react-hook-form错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!