1

How can I disable a whole section of a form in TypeScript/React?

Body:

I'm building a form in TypeScript (using React), and I want to disable an entire section of the form — similar to how Stack Overflow disables part of the UI when needed.

I tried adding disabled or aria-disabled to a , but it doesn't seem to have any effect, since those attributes don't actually disable interaction on non-interactive elements like divs.

Right now, I'm conditionally rendering the "disabled state" using something like:

{isDisabled ? (

{/* disabled form section */}

) : (

{/* active form section */}

)}

This works, but it feels a bit hacky or repetitive.

Is there a cleaner or more idiomatic way to "disable" an entire section of a form in React/TypeScript — ideally without having to set disabled manually on every single input?

Any suggestions or best practices would be appreciated.

1
  • What does "disable interaction on non-interactive elements like divs" mean? Do you have interactive components within the form which aren't form inputs? Commented Jul 31 at 17:22

1 Answer 1

0

You can use <fieldset/> tag to form a group of some form fields and pass the boolean to trigger the disabled state.

I dont know if this is the best practice, but get's the work done.

    <fieldset disabled={isDisabled}>
      <legend>Personal Details</legend>
      <label>
        Name:
        <input type="text" name="name" />
      </label>
      <label>
        Email:
        <input type="email" name="email" />
      </label>
    </fieldset>

Also if you don't want to render them at all, I would form an array of the form fields (if I have almost similar stylings), map it and conditionally render only the fields which I want like.

elements
  .filter((data) => !data.disabled)
  .map((data, i) => <FormInput key={i} data={data} />);
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.