Concatenate the names of yup and react-hook-form when using an array of objects
P粉743288436
P粉743288436 2023-08-17 21:56:44
0
1
486
<p><br /></p><h4>I am trying to combine <code>react-hook-form</code> with <code> via <code>register</code> ;yup</code> pattern was connected, but an error was encountered. My goal is to pass a name like <code>exampleArray${index}.exampleProp</code> since I will be rendering the input box in a loop. </h4> <p>A simple example:</p> <pre class="brush:php;toolbar:false;">import * as yup from "yup"; import { useForm } from "react-hook-form"; import { yupResolver } from "@hookform/resolvers/yup"; const schema = yup.object().shape({ exampleArr: yup.array().of( yup.object().shape({ exampleProp:yup.string() }) ) }); type FormValues ​​= yup.InferType<typeof schema>; export default function App() { const methods = useForm<FormValues>({ resolver: yupResolver(schema) }); return ( <input type="text" {...methods.register("exampleArr[0].exampleProp")} /> // error here ); }</pre> <blockquote> <p>Parameter of type '"exampleArr[0].exampleProp"' cannot be assigned to type '"exampleArr" | <code>exampleArr.${number}</code> | <code>exampleArr.${ number}.exampleProp</code>'. </p> </blockquote> <p>Example in codesandbox: https://codesandbox.io/s/funny-orla-97p8m2?file=/src/App.tsx</p>
P粉743288436
P粉743288436

reply all(1)
P粉312631645

You need to tell what the type of exampleArr.${number} is:

For example, I just tested this on your sandbox and it worked perfectly:

<input type="text" {...methods.register("exampleArr[0].exampleProp" as any)} />
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template