'When I try to use controlled data, schema isn't working at all
I'm working on a form with controlled components using state, but I don't understand how to allow my yup formschema working. When components are uncontrolled, it works like a charm. But when I try to use controlled data, schema isn't working at all.
The code of App.js :
import { useState } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup'
import * as Yup from 'yup';
import { TextField } from '@mui/material';
import "./styles.css";
export default function App() {
const formSchema = Yup.object().shape({
address_1: Yup.string()
.required("Field is required")
.max(10, "Field too long"),
});
const formOptions = {
resolver: yupResolver(formSchema),
mode: 'onChange',
defaultValues: {
address_1: "My address",
}
};
const {
handleSubmit,
formState: { errors },
control,
register
} = useForm(formOptions);
const onSubmit = (data) => {
console.log(address1);
}
const [address1, setAddress1] = useState( "My address" );
return (
<div className="App">
<form onSubmit={handleSubmit(onSubmit)}>
<div className="row mt-3">
<div className="form-group col-md-6">
<Controller
name="address_1"
control={control}
render={({ field, formState }) => (
<TextField
{...field}
fullWidth
required
label="Insert an address"
error={!!formState.errors?.address_1}
helperText={formState.errors?.address_1?.message}
value={address1}
onChange={(event) => setAddress1( event.target.value )}
/>
)}
/>
<input type="submit" value="Send"/>
</div>
</div>
</form>
</div>
);
}
Here is a codeSandbox to demonstrate the implementation. The unique field must be required and with a maximum of characters of 10 characters. I tried a lot of combination, but I'm actually not able to find my mistake.
If anyone has a suggestion or a sample to let me understand what I'm missing... :-)
Thanks in advance for any help on this problem.
Solution 1:[1]
It seems that it can be solved.
Please comment out as follows...
// value={address1}
// onChange={(event) => setAddress1(event.target.value)}
The reason is that TextField
does not try to connect to react-hook-form, but connects to "state".
In this case, the following state seems unnecessary
const [address1, setAddress1] = useState ("My address");
I tried, but the schema worked fine
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rin |