2

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.

2
  • What do you mean by rows? Is the above component used as a single row or has multiple rows inside it. Commented Jul 7, 2021 at 17:21
  • Easiest way: you have to make sure each row controls its own state, basically each row can be a component that will have its own setState pair (if you really need both). Commented Jul 7, 2021 at 17:22

1 Answer 1

1

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>;
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.