Search code examples
reactjsvalidationyupdisable

Using Reacthookforms and Yup to disable fields dynamically


I have been a junior for around 3 weeks and have come to my first problem I cant solve on my own and my senior is away for 2 weeks.

I cant seem to get react hook forms to disable and enable field b once field a is valid.

I tried using isValid() but that returns a promise so cant recheck once field becomes invalid.

I have tried seeing if there are errors and disabling and enabling based on if there are errors which works to a degree but doesn't disable the field if it is empty which in my case would be invalid.

<input disabled={errors.name ? true : false} />

https://codesandbox.io/embed/beautiful-mclean-ewmdu?fontsize=14&hidenavigation=1&theme=dark

Any advice would be gratefully recieved


Solution

  • so I would use watch() function from react hook form here. I'm watching input value of full name storing it in a variable and using that as a way to check if I should disable input or not. Here's a not complete code example below:

     const {
        register,
        handleSubmit,
        watch, // Don't forget to pull watch from useForm
        formState: { errors }
      } = useForm({
       mode: "onChange",
        resolver: yupResolver(validationSchema)
      });
      // fullName variable value will change anytime there's update to input field
      const fullName = watch('fullname');
    
      const onSubmit = (data) => console.log(data);
      ...etc
      return (
        ...etc
         <input
          disabled={!fullName || fullName.length === 0 || erros.fullName}
          className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
          name="coolname"
          {...register("coolname")}
        />
      ...etc