Stautenberg
Stautenberg

Reputation: 101

React how to change button back to disabled when input empty

From https://react-hook-form.com/api/useform/formstate I am using the isValid state to check if input matches the rules

        <form>
          <Controller
            name="username"
            control={control}
            rules={{
              minLength: {
                value: 2,
                message:
                  'Tx',
              },
              pattern: {
                value:
                  /^([A-Za-z0-9_](?:(?:[A-Za-z0-9_]|(?:\.(?!\.))){0,28}(?:[A-Za-z0-9_]))?)/,
                message:
                  'x',
              },
            }}
            render={({ field: { ref, ...field } }) => (
              <SecondaryInput
                name="username"
                errors={errors}
                innerRef={ref}
                {...field}
              />
            )}
          />

          <PrimaryButton
            disabled={!isDirty || !isValid}
            type="submit"
          >
            Test Submit
          </PrimaryButton>
        </form>

And it works:

  1. Button is disabled (empty input)
  2. I type
  3. Button not disabled anymore

But when I delete everything (empty input) the button is not disabled. The isValid state remains true

It is probably due to the isDirty state but I don't know how the code works without the isDirty state

Upvotes: 0

Views: 55

Answers (1)

Saurav Ghimire
Saurav Ghimire

Reputation: 540

The information that you gave is quite not enough. Make sure that you are using a function to handle changes to your input field using the onChange property. Use the useState function to declare and store the value of the user input and the boolean values isDirty and isValid.

On your function that handles the change to the input field, make sure to check whether the input is valid/dirty or not and update the boolean variables as needed.

Since you declared your variables with useState, react updates the state and your web page should behave the way you want it to.

Upvotes: 1

Related Questions