How can I make a React-Bootstrap radio group required with HTML validation?

Viewed 1596

I'm using a pair of React-Bootstrap radio buttons in my app. I need to require that the user make a selection. However, adding required as seen here doesn't have the same effect that it would on an HTML radio input.

<Form.Check inline label="One" type='radio' required />
<Form.Check inline label="Two" type='radio' required />

How can I apply the HTML5 required attribute here? I'm looking for basic HTML5 validation, not React validation.

2 Answers

Step 1: Set flag in state, default to true

class HaveAccount extends Component {
  state = {
    flag: true,
  };
  render() {
    const { haveAccount, updateHaveAccount } = this.props;
    const handleChange = (e) => {
      if (this.state.flag)
        this.setState((prevState) => ({ ...prevState, flag: false }));
      updateHaveAccount({ value: e.target.value });
    };
    return (
        <div>
          <Form className="d-flex flex-column justify-content-center">
            <Form.Group as={Row}>
              <Col sm={{ span: 7, offset: 5 }}>
                <Form.Check
                  type="radio"
                  label="YES"
                  name="haveAccountRadios"
                  value={true}
                  id="haveAccountRadios1"
                  onChange={handleChange}
                />
                <Form.Check
                  type="radio"
                  label="NOPE"
                  name="haveAccountRadios"
                  value={false}
                  id="haveAccountRadios2"
                  onChange={handleChange}
                />
              </Col>
            </Form.Group>
            <Form.Group className="d-flex justify-content-center">
              <Link
                className={`button button-link ${
                  this.state.flag ? "disabled" : ""
                }`}
                to="/login"
              >
                Next
              </Link>
            </Form.Group>
          </Form>
        </div>
    );
  }
}

Step 2: I'm conditionally adding className disabled based on the flag. Flag only gets updated first time handleChange executes.

Step 3: Add CSS

.disabled {   
  background-color: #ccc;
  pointer-events: none; 
}

Had the same issue as you, it's actually very simple and it's a shame they don't specify in the documentation.

Give them all the same name.


<Form.Check name="grouped" required inline label="One" type='radio' />
<Form.Check name="grouped" required inline label="Two" type='radio' />

Related