How To Checked Multiple Checkbox In React.js?
I am using react antd . I have got array of objects that's groupKey .I am mapping checkbox by using Groupkey and also I have got two different types of checkbox . One is Select All
Solution 1:
Here is what I have come up with
https://codesandbox.io/s/check-all-ant-design-demo-6cm2v?file=/index.js
importReactfrom"react";
importReactDOM from"react-dom";
import"antd/dist/antd.css";
import"./index.css";
import { Checkbox } from"antd";
constCheckboxGroup = Checkbox.Group;
classAppextendsReact.Component {
state = {
groupKey: [
{ id: 1, key: "manage_books", label: "books" },
{ id: 2, key: "manage_journals", label: "journals" },
{ id: 3, key: "manage_deals", label: "deals" }
],
checked: {},
output: [],
indeterminate: true,
checkAll: false
};
onCheckAllChange = e => {
const { groupKey } = this.state;
const checked = groupKey.reduce((prev, curr) => {
return { ...prev, [curr.key]: e.target.checked };
}, {});
this.setState({ checked, checkAll: e.target.checked });
};
checkAll = () => {};
onChange = (e, value) => {
// this.setState({// checked: e.target.checked,// output: this.state.output.concat(value)// });this.setState(
state => ({
checked: { ...state.checked, [value]: e.target.checked }
}),
() => {
const { checked, groupKey } = this.state;
const values = Object.values(checked);
if (values.length === groupKey.length && values.every(v => v)) {
this.setState({ checkAll: true });
} else {
this.setState({ checkAll: false });
}
}
);
};
render() {
console.log(this.state.output);
const { checked, checkAll } = this.state;
return (
<div><divclassName="site-checkbox-all-wrapper">
Select All
<Checkbox
// indeterminate={this.state.indeterminate}onChange={this.onCheckAllChange}checked={checkAll}
/></div>
{this.state.groupKey.map(item => (
<divclassName="userpermission-content"key={item.id}>
{item.label}
<CheckboxonChange={e => this.onChange(e, item.key)}
value={item.key}
checked={checked[item.key]}
/>{" "}
</div>
))}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("container"));
Post a Comment for "How To Checked Multiple Checkbox In React.js?"