I have a table where the first column has a checkbox in each row. I want to disable a button if more than one checkbox is selected or no check box is checked. It should be active only if 1 checkbox is checked
import React, { useState } from "react";
import "./styles.css";
function Example() {
const [boxes, setBoxes] = useState([]);
function handleChange(e) {
const {
parentNode: { children }
} = e.target;
const index = [...children].indexOf(e.target);
const newState = [...boxes];
newState[index] = !newState[index];
setBoxes(newState);
}
function isDisabled() {
const len = boxes.filter((box) => box).length;
return len === 0 || len > 1;
}
return (
<div className="App">
<button disabled={isDisabled()}>Click Me</button>
<table>
<thead>
<th>One</th>
<th>Two</th>
<th>Three</th>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" onChange={handleChange} />
</td>
<td> two data</td>
<td> three data</td>
</tr>
<tr>
<td>
<input type="checkbox" onChange={handleChange} />
</td>
<td> two data</td>
<td> three data</td>
</tr>
<tr>
<td>
<input type="checkbox" onChange={handleChange} />
</td>
<td> two data</td>
<td> three data</td>
</tr>
</tbody>
</table>
</div>
);
}
export default Example;
I was able to make this work if all the checkboxes are in the same parent node. But in the case of a table, each checkbox is in a separate row.