简体   繁体   中英

React Bootstrap custom checkbox without id?

I'm having a hard time understanding why this simple Bootstrap custom checkbox doesn't work. I'm using React, Bootstrap, and React-Boostrap.

import React from "react";
import ReactDOM from "react-dom";
import { Button, Form, FormCheck } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";

function App() {
  return (
    <div className="p-3">
      <FormCheck custom label="Checkbox">
      </FormCheck>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));

Online Example

Adding id="test" to FormCheck seems to cause the checkbox to work, but is is possible to not have to use id ? (The checkbox is used within the component of an object in my actual code, and it would be unnecessarily complicated to come up with a unique id for every checkbox)

Try this:

<FormCheck>
  <FormCheck.Label>Allow us to contact you?
    <FormCheck.Input isInvalid type={radio} />
  </FormCheck.Label>
  <Feedback type="invalid">Yo this is required</Feedback>
</FormCheck>

The basic idea is that you need to change the way it's rendered. By default it has label and input on the same level, meaning that you have to bind them using id and for . And you want to put input inside of the label to bind it without id .

You might need some custom css as mentioned in this answer: https://stackoverflow.com/a/57901478/4536543

If you do want to use the React Bootstrap components you will have to use an ID to use the FormCheck component. This is as within the FormCheck component the ID is used to call useContext() so that the component can access the element through the DOM.

Source Code:

/** A HTML id attribute, necessary for proper form accessibility. */
id: PropTypes.string,

const { controlId } = useContext(FormContext);
const innerFormContext = useMemo(
  () => ({
    controlId: id || controlId,
    custom,
  }),
  [controlId, custom, id],
);

Source

Ended up finding the solution here (Normal bootstrap 4)

<FormCheck custom>
  <FormCheck.Label>
    <FormCheck.Input type="checkbox" name="checkbox-name" />
      <div className="custom-control-label"></div>
    </FormCheck.Label>
</FormCheck>

It involves a bit of a work around, nesting labels with checkboxes. Bootstrap 4 custom buttons seem to have strange behaviour

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM