search

Home  >  Q&A  >  body text

Concatenate the names of yup and react-hook-form when using an array of objects

<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粉743288436P粉743288436454 days ago463

reply all(1)I'll reply

  • P粉312631645

    P粉3126316452023-08-18 20:03:26

    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)} />

    reply
    0
  • Cancelreply