简体   繁体   中英

Making the entire div to behave as a checkbox using React

I am having this condition where I display a list of checkboxes . Here I want the entire div to act as a checkbox. Currently it works only on the checkbox and the label . Instead I want the entire div to be made checked/unchecked.

Help would be appreciated

Sandbox: https://codesandbox.io/s/modest-meninsky-9lcmb

Code

import React from "react";
import ReactDOM from "react-dom";
import { Checkbox } from "semantic-ui-react";
import "./styles.css";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [
        { display: "CB1", checked: false, name: "cb1" },
        { display: "CB2", checked: false, name: "cb2" },
        { display: "CB3", checked: false, name: "cb3" }
      ]
    };
  }

  handleItemClick = (event, data) => {
    const index = this.state.data.findIndex(item => item.name === data.name);
    const optionsArr = this.state.data.map((prevState, i) =>
      i === index
        ? {
            display: prevState.display,
            name: prevState.name,
            checked: !prevState.checked
          }
        : prevState
    );
    this.setState({ data: optionsArr });
  };


  render() {
    return (
      <div>
        <div className="menu-item-holder">
          {this.state.data.map((item, i) => (
            <div className="menu-item" key={i}>
              <Checkbox
                onChange={this.handleItemClick}
                checked={item.checked}
                label={item.display}
                name={item.name}
              />
            </div>
          ))}
        </div>
      </div>
    );
  }
}

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

styles.css

.menu-item-holder {
  border: 1px solid #ccc;
  width: 150px;
}
.menu-item {
  padding: 5px 10px;
  border-bottom: 1px solid #ccc;
  cursor: pointer;
}

Just increase the width of label with parent width. Add below css in styles.css,

.ui.checkbox input.hidden+label {
  width:150px;
}

Just add a width to .ui.checkbox .

.ui.checkbox {
   width: 100%;
}

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