Issue
I need to be able to select one box or the other by means of checking one will uncheck the other, but I also need it so that I can select neither, which is why I opted for not using radio buttons.
This is an example of how the checkboxes look now.
import Table from 'react-bootstrap/Table';
import { useState } from "react";
function myfunc() {
const [checkedTable, setCheckedTable] = useState(true);
const [checkedSkip, setCheckedSkip] = useState(false);
const handleChangeTable = (e) => {
console.log(e.target)
setCheckedTable(!checkedTable);
if (checkedSkip) {
setCheckedSkip(!checkedSkip)
}
}
const handleChangeSkip = (e) => {
setCheckedSkip(!checkedSkip);
if (checkedTable) {
setCheckedTable(!checkedTable)
}
}
return (
<Table style={{width: "100%"}} striped>
<thead>
<tr>
<th>QNAME</th>
<th>Table</th>
<th>Fills/Skips</th>
</tr>
</thead>
<tbody>
{(typeof questions === 'undefined') ? (
<p>Loading...</p>
) : (
questions.map((question, i) => (
<tr key={i}>
<td>{question}</td>
<td>
<input
type="checkbox"
name={question}
id={question + " table"}
checked={checkedTable}
onChange={handleChangeTable}
/>
</td>
<td>
<input
type="checkbox"
name={question}
id={question + " skip"}
checked={checkedSkip}
onChange={handleChangeSkip}
/>
</td>
</tr>
))
)}
</tbody>
</Table>
)
}
export default myfunc;
I have tried mapping the useState and that's why you see e in the onChange functions, but nothing worked so far.
Solution
You could manage an object for each type of checkbox, something like:
const [checkedTable, setCheckedTable] = useState({});
const [checkedSkip, setCheckedSkip] = useState({});
When rendering you could call a change handler like handleChangeCheckbox
which passes the question
as well as the type of checkbox.
questions.map((question, i) => (
<tr key={i}>
<td>{question}</td>
<td>
<input
type="checkbox"
name={question}
id={question + " table"}
checked={checkedTable[question]}
onChange={() => handleChangeCheckbox(question, "table")}
/>
</td>
<td>
<input
type="checkbox"
name={question}
id={question + " skip"}
checked={checkedSkip[question]}
onChange={() => handleChangeCheckbox(question, "skip")}
/>
</td>
</tr>
))
You could then update the state of each checkbox accordingly:
const handleChangeCheckbox = (question, type) => {
setCheckedTable((prev) => ({
...prev,
[question]: type === "table"
}));
setCheckedSkip((prev) => ({
...prev,
[question]: type === "skip"
}));
};
Answered By - Ben
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.