Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check/uncheck a list of checkboxes in react

I have a room page and in that page I have a list of sensors attached to that room, those sensors can be selected using a checkbox, like so:

<div className="checkboxRowContent">
  {sensors.map(s => {
    return (
      <div className="checkboxElementWrapper" key={s.id}>
        <label htmlFor={`sensor${s.id}`}>
          <div className="checkboxLabel">
            <Link to={`/sensors/edit/${s.id}`}>{s.name}</Link>
          </div>
          <input
            type="checkbox"
            id={`sensor${s.id}`}
            name="sensorId"
            value={s.id}
            checked={s.roomId === values.id}
            onChange={handleCheckbox}
          />
          <span className="checkbox" />
        </label>
      </div>
    );
  })}
</div>

the problem is - this approach prohibits me from unchecking the checkbox (so if in db that sensor is attached to that room - that's it). How could I rewrite this so that I can check/uncheck this checkbox?

like image 863
Xeen Avatar asked Jan 30 '18 11:01

Xeen


People also ask

How do you check and uncheck a checkbox in Reactjs?

1- You can use ref with check boxes, and onClick of button, by using ref you can unCheck the box. 2- You can use controlled element, means store the status of check box inside a state variable and update that when button clicked.

How do you check if checkbox is checked in React?

Use the target. checked property on the event object to check if a checkbox is checked in React, e.g. if (event. target. checked) {} .

How do you handle checkboxes in React?

In React, the best way to do this is via the useState hook. This is different from normal JavaScript because we are unable to access the value of the checkbox directly from its DOM component: /* Create a checkbox functional component. Toggle the text of a paragraph with the checkbox using the 'useState' hook.


2 Answers

in the class you must have state for that,

a sample would be somewhat like this

export default class yourComponent extends React.Component {

  state = {
    checkedBoxes: []
  }

  handleCheckbox = (e, s) => {
    const checkedBoxes = [...this.state.checkedBoxes];
    if(e.target.checked) {
      checkedBoxes.push(s)
    } else {
      const index = checkedBoxes.findIndex((ch) => ch.roomId === s.roomId);
      checkedBoxes.splice(index, 1);
    }
    this.setState({checkedBoxes});
  }


  render() {

    return(
      <div className="checkboxRowContent">
      {sensors.map(s => {
          return (
            <div className="checkboxElementWrapper" key={s.id}>
              <label htmlFor={`sensor${s.id}`}>
                <div className="checkboxLabel">
                  <Link to={`/sensors/edit/${s.id}`}>{s.name}</Link>
                </div>
                <input
                  type="checkbox"
                  id={`sensor${s.id}`}
                  name="sensorId"
                  checked={checkedBoxes.find((ch) => ch.roomId === s.roomId)}
                  onChange={(e) => handleCheckbox(e, s)}
                />
                <span className="checkbox" />
              </label>
            </div>
          );
        })}
      </div>
    )
  }
}

A state, checkedBoxes for getting all selected checkboxes.

A handler handleCheckbox for handling checkbox clicks,

like image 68
Aswin Ramesh Avatar answered Oct 16 '22 15:10

Aswin Ramesh


You have handleCheckBox and a controlled component. We don't see what you do in the event handler but when it's controlled, you can check it by altering your sensors array (if in state/props) so s.roomId === values.id will be true.

If you don't want it to be controlled, you can probably use defaultChecked which will let you work with it in a different way.

see https://reactjs.org/docs/forms.html#controlled-components

like image 37
Dimitar Christoff Avatar answered Oct 16 '22 15:10

Dimitar Christoff