Search code examples
javascripthtmlcssreactjssemantic-ui-react

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;
}


Solution

  • Just add a width to .ui.checkbox.

    .ui.checkbox {
       width: 100%;
    }