noobcode0000
noobcode0000

Reputation: 243

How to enable/disable input field depending on checkbox with Reactstrap

On the page I have with reactstrap, I have a checkbox and when this checkbox is checked, I would like the input field to be enabled and if it is unchecked then the input field disabled. How would I go abouts doing this? This is my current code:

import {
    Input,
    FormGroup,
    FormText,
    Form,
    Label,
    Button,
  } from "reactstrap";

function HelloWorld() {
   let mpinput;
      if ((e) => e.target.checked === true) {
        mpinput = <Input type="text" name="pmInput" id="pmInput"/>
      } else {
        mpinput = <Input type="text" name="pmInput" id="pmInput" disabled />
      }
   return (
   ...
   <FormGroup check>
       <Label check>
           <Input type="checkbox" id="mpCheckbox" onChange={(e) => console.log(e.target.checked)} />
           <Label for="mpinput">Input Field</Label>
           {mpinput}
       </Label>
   </FormGroup>
   )
}
export default HelloWorld;

I know I have done something wrong since it is not working how I would like it to, and my guess is that its something to do with the 'if' statement or I am missing something. Sorry if this is a beginners question, I am still working my way through react. Any help would be appreciated.

Upvotes: 1

Views: 1887

Answers (1)

iunfixit
iunfixit

Reputation: 994

You need to use state to keep track of the check status

function HelloWorld() {
   const [isChecked, setIsChecked] = React.useState(false)

   return (
   ...
   <FormGroup check>
       <Label check>
           <Input type="checkbox" id="mpCheckbox" onChange={(e) => setIsChecked(e.target.checked)} />
           <Label for="mpinput">Input Field</Label>
           <Input type="text" name="pmInput" id="pmInput" disabled={isChecked} />
       </Label>
   </FormGroup>
   )
}
export default HelloWorld;

In your code the if has no access to the e variable, it is only defined in the scope of the onChange callback, you need to use it to set the state inside of that callback, then you are able to use the checked status somewhere else.

I moved the input on the return, but your if would also work with the isChecked

Upvotes: 1

Related Questions