React functional component: enable/disable button based on a state value Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of React functional component: enable/disable button based on a state value without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I use a component where I use the following code to update the ‘active’ flag value. I have a problem with updating the Button when the ‘active’ flag changes its value. At the moment, when ‘active’ is false, the button is disabled, then I select true and the button gets enabled. However, I can’t make the button disabled again when selecting false. What should I change in order to enable/disable the Button whenever the active flag value changes?

const [active, setActive] = useState(props.limit.active)

const onSubmit = (e) => {
    const form = event.currentTarget
    if (form.checkValidity() === true) {
      e.preventDefault()

      if (props.onSubmit) {
        props.onSubmit({
          active: active,
        })
      }
    }
  }

  const handleActiveChange = (event) => {
    setActive(event.target.value)
  }

 return <Form onSubmit={onSubmit}>
  <Form.Group controlId='formGridActive'>
      <Form.Label>Active</Form.Label>
      <Form.Control name='active' value={active} as='select' onChange={handleActiveChange}>
        <option>true</option>
        <option>false</option>
      </Form.Control>
    </Form.Group>

    <Form.Group>
      <Button variant="primary" type="submit" disabled={!active} >Submit </Button>
    </Form.Group>

  </Form >
}

Answer

Option tag must have “value” property. Check this: https://www.w3schools.com/tags/att_option_value.asp

We are here to answer your question about React functional component: enable/disable button based on a state value - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji