PASSWORD RESET

Your destination for complete Tech news

How to enable or disable an input in React JS?

1.89K 0
< 1 min read

You can enable or disable an input in React by utilizing the disabled attribute on the input element. The disabled attribute prevents user interaction with the input and typically greys out the input element. Here’s how you can do it:

import React, { useState } from 'react';

function InputEnableDisable() {
  const [isInputEnabled, setIsInputEnabled] = useState(true);

  const toggleInputEnabled = () => {
    setIsInputEnabled((prevEnabled) => !prevEnabled);
  };

  return (
    <div>
      <input type="text" disabled={!isInputEnabled} />
      <button onClick={toggleInputEnabled}>
        {isInputEnabled ? 'Disable' : 'Enable'} Input
      </button>
    </div>
  );
}

export default InputEnableDisable;

In this example, the InputEnableDisable component uses the useState hook to manage the state of whether the input is enabled or disabled. The input’s disabled attribute is bound to the inverse of the isInputEnabled state. The button’s text and the onClick event are also set up to toggle the isInputEnabled state.

When the button is clicked, the input’s enabled/disabled state changes accordingly.

Keep in mind that when an input is disabled, its value won’t be submitted along with the form, so you might want to consider how this interacts with your form submission logic.

If you’re working with form libraries like formik or react-hook-form, they might provide their own ways to manage input enabling/disabling.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.