1

I am new to using React and React Hook Form, and am running into a typescript error (TS:2345) when I try to register a new input after assigning defaultValues for the form. I am creating a resume generator that watches for changes in the inputs and dynamically updates it on the resume.

The default value I am using is formatted like this:

export const defaultData = {
    name: 'John Doe',
    email: '[email protected]',
    number: '416-123-4567',
    address: 'California'
}

In my App component, I add my defaultValues with useForm()

function App(): JSX.Element {
  const { register, setValue, watch } = useForm({ defaultValues: defaultData });

Then, when I go on to register the inputs, i get the error:

Argument of type 'string' is not assignable to parameter of type '"number" | "name" | "email" | "address" (TS:2345)'

inputs={section.inputs.map((iField) => {
          const field = iField.field; //field is the name of the input property
          return (
            <div key={iField.id} className="inputField">
              <label>{iField.title}</label>
              <input
                {...register(field)}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                  setValue(field, e.target.value);
                }}
              ></input>
            </div>
          );
        })}

Any idea why I am getting this error? The properties in defaultData are all strings

1 Answer 1

0

The register function accept only string. Your field might be a string but with only specific list of strings "number" | "name" | "email" | "address". So you have compatibility issue as string can be anything else...

You might want to change {...register(field)} to {...register(field as string)}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.