Tony
Tony

Reputation: 77

How can I disable an input textbox when a checkbox is checked?

I'm new to React and looking for a clue to disable an input text box when a corresponding checkbox is ticked. Below is my code:

const [checked, setChecked] = useState(false);
const [disable, setDisable] = useState(true);

<div>
  <div>
    <input
      type="checkbox"
      value={!checked}
      onChange={() => setDisable(!disable)}
      disable={!disable}
    />
  </div>

  <div>
    <input
      type="text"
      placeholder="Enter correct detail"
      disabled={!disable}
      onChange={() => setChecked(true)}
    />
  </div>
</div>;

The above code works for only a row. How do I implement this logic to be able to work for several other rows.

Upvotes: 2

Views: 421

Answers (1)

underscore
underscore

Reputation: 6887

You can create an another component and isolate the state to that

Component: InputWithCheckBox

const InputWithCheckBox = () => {

  const [checked, setChecked] = useState(false);
  const [disable, setDisable] = useState(true);

  return (
    <>
      <div>
        <input
          type="checkbox"
          value={!checked}
          onChange={() => setDisable(!disable)}
          disable={!disable}
        />
      </div>

      <div>
        <input
          type="text"
          placeholder="Enter correct detail"
          disabled={!disable}
          onChange={() => setChecked(true)}
        />
      </div>
    </>
  )

}

Import the InputWithCheckBox where you want to display it. Then you can add multiple rows as you want

<div>

  <InputWithCheckBox/>
  <InputWithCheckBox/>


</div>;

Upvotes: 1

Related Questions