1

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for the help

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.