How to combine ant-design checkbox and table? - javascript

I have a table that looks like this:
It is filled from the data array. As you can see in this object there is a done field. I want to make the check-boxes marked depending on the value of the done field. And of course I want the checkbox value to change the field value in the object.
Here's my code:
<template>
<a-table :columns="columns" :dataSource="data">
<span slot="action">
<a-checkbox :checked="checked" #click="onChange"> </a-checkbox>
</span>
</a-table>
</template>
<script>
const columns = [
{
title: "Student",
dataIndex: "Student",
key: "Student"
},
{
title: "Action",
key: "action",
width: "1%",
scopedSlots: { customRender: "action" }
}
];
const data = [
{
key: "1",
Student: "John Brown",
done: false
},
{
key: "2",
Student: "John Brown",
done: true
},
{
key: "3",
Student: "John Brown",
done: false
},
{
key: "4",
Student: "John Brown",
done: true
}
];
export default {
data() {
return {
data,
columns,
checked: false
};
},
methods: {
onChange(e) {
this.checked = e.target.checked;
},
toggleChecked() {
this.checked = !this.checked;
}
}
};
</script>

As per Ant Table, you need to use slot-scope="text, record" to biding the value in <a-checkbox >. Like below
<a-checkbox :checked="record.done" #click="onChange(record)"></a-checkbox>
You can check here with working codesandbox example.
Code Snippet
<template>
<a-table :columns="columns" :dataSource="data">
<span slot="action" slot-scope="record">
<a-checkbox :checked="record.done" #click="onChange(record)"></a-checkbox>
</span>
</a-table>
</template>
<script>
const columns = [{
title: "Student",
dataIndex: "Student",
key: "Student"
},{
title: "Action",
key: "action",
width: "1%",
scopedSlots: { customRender: "action" }
}],
data = [
{ key: "1", Student: "John Brown", done: false },
{ key: "2", Student: "John Brown", done: true },
{ key: "3", Student: "John Brown", done: false },
{ key: "4", Student: "John Brown", done: true }
];
export default {
name: "App",
data() {
return {
data,
columns
};
},
methods: {
onChange(record) {
record.done = !record.done;
}
}
};
</script>

Related

How can I put the data inside the table?

I am using mui-datatables. I can already retrieve the data correctly. However, I am quite lost on how to display the data address, ID, and name, and date only in the table.
codesandbox link :https://codesandbox.io/s/infallible-feistel-bki5h?file=/src/App.js
This is the data in a JSON format.
[
{
name: "Sample Name",
items: {
id: "34234242",
selectedItem: "Item",
date: { seconds: 1636905600, nanoseconds: 0 },
item1: true,
item2: false,
},
address: "Ayala",
email: "sample email",
phone: "823840820943",
},
];
Below are the codes.
const filter = users.filter((d) => d?.items?.item2 == false);
const filtered = selection.filter((f) => f?.items?.date <= new Date());
return (
<div>
{" "}
<MUIDataTable title={"List"} columns={columns} data={filtered} />
</div>
);
};
export default UserTable;
You need columns options where you include address, ID, name, and date. You can also hide column (using display: false) that are included into your column list. please the below example and you can check MUI Datatable documentation too.
import MUIDataTable from "mui-datatables";
const columns = [
{
name: "name",
label: "Name",
options: {
filter: true,
sort: true,
}
},
{
name: "company",
label: "Company",
options: {
filter: true,
sort: false,
}
},
{
name: "city",
label: "City",
options: {
filter: true,
sort: false,
display: false,
}
},
{
name: "state",
label: "State",
options: {
filter: true,
sort: false,
}
},
];
const data = [
{ name: "Joe James", company: "Test Corp", city: "Yonkers", state: "NY" },
{ name: "John Walsh", company: "Test Corp", city: "Hartford", state: "CT" },
{ name: "Bob Herm", company: "Test Corp", city: "Tampa", state: "FL" },
{ name: "James Houston", company: "Test Corp", city: "Dallas", state: "TX" },
];
const options = {
filterType: 'checkbox',
};
<MUIDataTable
title={"Employee List"}
data={data}
columns={columns}
options={options}
/>
Update based on your comment
You need to consider two things:
Need to use customBodyRender to show complex json data like items.SelectedItem
{
name: "items",
label: "Item",
options: {
filter: true,
sort: true,
customBodyRender: (value, tableMeta, updateValue) => {
console.log(value, tableMeta, updateValue, "test");
return value.selectedItem;
}
}
}
Need to use setRowProps to show background color of selected row based on condition. you need options to use setRowProps
const options = {
filter: true,
filterType: "dropdown",
fixedSelectColumn: false,
rowHover: false,
setRowProps: (row, dataIndex, rowIndex) => {
return {
style: row[1] === "Item" ? { backgroundColor: "skyblue" } : {}
};
}
};
Here is the complete example:
Updated Example in Codesandbox

I want to set checkbox to checked if the value comes true

I am using the Ant design tree component what my task is am a getting data from the backend in this tree structure and in children data I am getting key checked with the value true and false so I need to set checked if the checked key value is true if come false than not checked so checkbox will be checked by default if children data checked value is true you can also check codeSandBox link below.
const treeData = [
{
title: "First Watchlists",
key: "First Watchlists",
children: [
{ title: " Open Data", key: "Open Data", checked: true },
{
title: "Department of trade ",
key: "Department of trade ",
checked: true
},
{
title: "sanction List",
key: "sanction List",
checked: true
},
{ title: "People's Daily", key: "People's Daily", checked: true },
{
title: "People trades",
key: "People trades",
checked: true
}
]
},
{
title: "Second Watchlists",
key: "Second Watchlists",
children: [
{
title: "Second Service",
key: "Second Service",
checked: true
}
]
},
{
title: "Third Watchlists",
key: "Third Watchlists",
children: [
{
title: "National ",
key: "National ",
checked: false
},
{
title: "Militants List",
key: "Militants List",
checked: false
}
]
},
{
title: "Forth Watchlists",
key: "Forth Watchlists",
children: [
{ title: "FAT", key: "FAT", checked: true },
{ title: "FAC", key: "FAC", checked: false },
{ title: "SC", key: "SC", checked: false },
{
title: "Data Council",
key: "Data Council",
checked: true
},
{
title: " Sanctions List",
key: "Sanctions List",
checked: false
}
]
}
];
const Demo = () => {
const [expandedKeys, setExpandedKeys] = useState(["0-0-0", "0-0-1"]);
const [checkedKeys, setCheckedKeys] = useState(["0-0-0"]);
const [selectedKeys, setSelectedKeys] = useState([]);
const [autoExpandParent, setAutoExpandParent] = useState(true);
const onExpand = (expandedKeysValue) => {
console.log("onExpand", expandedKeysValue); // if not set autoExpandParent to false, if children expanded, parent can not collapse.
// or, you can remove all expanded children keys.
setExpandedKeys(expandedKeysValue);
setAutoExpandParent(false);
};
const onCheck = (checkedKeysValue) => {
console.log("onCheck", checkedKeysValue);
setCheckedKeys(checkedKeysValue);
};
const onSelect = (selectedKeysValue, info) => {
console.log("onSelect", info);
setSelectedKeys(selectedKeysValue);
};
return (
<Tree
checkable
onExpand={onExpand}
expandedKeys={expandedKeys}
autoExpandParent={autoExpandParent}
onCheck={onCheck}
checkedKeys={checkedKeys}
onSelect={onSelect}
selectedKeys={selectedKeys}
treeData={treeData}
/>
);
};
CodeSandBox Link
const buildCheckedKeys = () => {
const checked = [];
treeData.forEach((data) => {
data.children.forEach((item) => {
if (item.checked) {
checked.push(item.key);
}
});
});
return checked;
};
const [checkedKeys, setCheckedKeys] = useState(buildCheckedKeys);
Code can be found here

How to implement ascending or descending in the table with ant vue?

When you click ↑ on the second line, B moves to the first line and A moves to the second line. When you click ↓ on the first line, B moves to the second line, A moves to the first line, and each line clicks the ascending descending event. How to solve the above problem?
click ↑
click ↓
My code:
<template>
<a-table :columns="columns" :dataSource="data" #change="onChange">
<template slot="sort" slot-scope="text, record">
<span #click="orderFn(record)">↑</span>
<span #click="orderFn(record)">↓</span>
</template>
</a-table>
</template>
<script>
const columns = [
{
title: "Name",
dataIndex: "name"
},
{
title: "Age",
dataIndex: "age"
},
{
title: "sort",
dataIndex: "sort",
scopedSlots: { customRender: "sort" },
align: "center"
}
];
const data = [
{
key: "1",
name: "A",
age: 10
},
{
key: "2",
name: "B",
age: 20
},
{
key: "3",
name: "C",
age: 30
},
{
key: "4",
name: "D",
age: 40
}
];
function onChange(pagination, filters, sorter) {
console.log("params", pagination, filters, sorter);
}
export default {
data() {
return {
data,
columns
};
},
methods: {
onChange,
orderFn(record){
console.log(record)
}
}
};
</script>
The demo is as follows:
codesandbox

Ag-Grid Tree like structure attach cellClass to NodeChildren cells based on validation

In my Jquery&JavaScript, Angular, all seperate applications i have included Ag-Grid with columnDefs like below :-
this.columnDefs = [
{
headerName: "Age",
field: "age",
cellRenderer: "agGroupCellRenderer"
},
{
headerName: "Name",
field: "name"
},
{
headerName: "Year",
field: "year"
},
{
headerName: "Country",
field: "country"
}
];
and my row Data is like below
this.rowData = [
{
age: "Group A",
participants: [
{
age: 1,
name: "Michael Phelps",
year: "2008",
country: "United States"
},
{
name: "A.2",
age: 2,
year: "2008",
country: "United States"
},
{
name: "A.3",
age: 50,
year: "2008",
country: "United States"
}
]}];
this.getNodeChildDetails = function getNodeChildDetails(rowItem) {
if (rowItem.participants) {
return {
group: true,
children: rowItem.participants,
};
} else {
return null;
}
Now i want to attach cellClass to children grid values based on validation, like:-
if(age< 23 || ''){
return['classNameThatiWantToAttach'];
}
How to do this ??
You can make changes in below plunker also for this: -
https://plnkr.co/edit/lmjtuqfId4FIsTI5luL8?p=preview
You can do it like this
edit the column definitions and add a cellClass function to it
{
headerName: "Year",
field: "year",
editable: true,
cellClass: this.cellClass
}
Then define the function and add the conditions you need and return a string with the value of the class
cellClass(params) {
if (params.value >= 2015)
return "redClass"
}
Don't forget to add the css styling for the classes.
Example
Please see the updated plunkr showing a cell in red color as per validation of the age:
https://plnkr.co/edit/QZd2MM1LflQaruxdCmym?p=preview
this.columnDefs = [
// ...
{
headerName: "Age",
field: "age",
cellClassRules: this.getCssClass()
}
// ...
];
getCssClass(): {[cssClassName: string]: (Function | string)} {
return {
'invalid-age': this.validateAge(),
};
}

Combine Objects and place into array - JavaScript / React

I have multiple objects in an array. They each have a labelId assigned to them. If the label id is the same then I need to combine the objects by placing some of the values inside an array of the new combined object.
[
{
field: "legalName",
isOpened: false,
label: "Legal Name",
labelId: 1,
value: "John Doe"
},
{
field: "homeAddress1",
isOpened: false,
label: "Home Address",
labelId: 2,
value: "2343 Main Street"
},
{
field: "homeAddress2",
isOpened: false,
label: "Home Address",
labelId: 2,
value: "New York, NY"
}
]
What I want it to look like
[
{
isOpened: false,
label: "Legal Name",
labelId: 1,
values:
[
{field: "legalName", value: "John Doe"}
]
},
{
isOpened: false,
label: "Home Address",
labelId: 2,
values:
[
{field: "homeAddress1", value: "2343 Main Street"},
{field: "homeAddress2", value: "New York, NY"}
]
}
]
I am removing the field and value from the original object and placing it into an array of values for all objects regardless if they have the same labelId.
Code so far -
personalInfoArray.forEach(info => {
personalInfoArray.forEach(info2 => {
if ((info.labelId === info2.labelId) && (info.field !== info2.field)) {
info.values = [
{field: info.field, value: info.value},
{field: info2.field, value: info2.value}
]
}
})
})
I am looping through the same array twice in order to determine if the object has the same labelId, if success - create array. The issue is I'm not removing the properties and the other object still exists. Along with if they don't have the same labelId, nothing happens.
Thanks
This is an approach using the function Array.prototype.reduce to group the object by labelId and the function Object.values to extract the grouped objects.
let arr = [{ field: "legalName", isOpened: false, label: "Legal Name", labelId: 1, value: "John Doe" }, { field: "homeAddress1", isOpened: false, label: "Home Address", labelId: 2, value: "2343 Main Street" }, { field: "homeAddress2", isOpened: false, label: "Home Address", labelId: 2, value: "New York, NY" }],
result = Object.values(arr.reduce((a, {labelId, field, isOpened, label, value}) => {
(a[labelId] || (a[labelId] = {isOpened, label, labelId, values: []})).values.push({field, value});
return a;
}, Object.create(null)));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Categories