2

I am using react-hook-form with custom dynamic input fields array, it looks like the validation is working when I click on submit button, but it doesn't show the error messages, I am creating the state as:

const [formFields, setFormFields] = useState([
{
  height: 45,
  label: "tv",
  placeholder: "555",
  name: "tv",
  maxWidth: 203,
  error: errors.tv,
  value: ""
},
{
  height: 45,
  label: "radio",
  placeholder: "90%",
  name: "radio",
  maxWidth: 126,
  error: errors.radio,
  value: ""
},
{
  height: 45,
  label: "instagram",
  placeholder: "90%",
  name: "instagram",
  maxWidth: 126,
  error: errors.instagram,
  value: ""
}

]);

and creating the input as:

{formFields.map((item, index) => {
      return (
        <div key={index}>
          <TextInput
            name={item.name}
            label={item.label}
            height={item.height}
            placeholder={item.placeholder}
            error={item.error}
            value={item.value}
            inputRef={register({
              required: true
            })}
            onChange={fieldOnChange(index)}
          />
          {item.error && <span>Enter a valide value</span>}
        </div>
      );
    })}

you can check the demo

any help please?

0

1 Answer 1

2

It's because you formFields in useState. It runs only one time. Show it already captures errors value i.e first initially value. You need to either use useEffect to keep track change of error value or change condition of item.error to directly errors.

react-hook-form uses its errors for validation i.e in your case it should be

{errors[item.name] && <span>Enter a valid value</span>}

Here is demo link : https://codesandbox.io/s/blue-shape-pv8jf

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.