How can I put the data inside the table? - javascript

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

Related

MUI datatable sorting column

I have a column that is basically an object, I display the value I want to display, but the sort does not work for that column.
Attach an example so I can explain myself a little better.
for example:
const [data, setData] = useState([
{
ID: "A001",
Name: "Joe James",
Amount: "$300,000",
Purpose: "$220,000",
Tib: 12 + "years",
details: {Score: "620-670" , Name:"Joe James"},
Score: "620-670",
Phone: "9292132019",
Mail: "Nole#temp.io",
State: "TX",
Opening: "11.11.2021",
Pf: "Priority urgent",
Flags: "In Progress",
Ls: "DorAff",
Company: "Dit",
Ras: "...",
},
{
ID: "A001",
Name: "Joe James",
Amount: "$300,000",
Purpose: "$220,000",
Tib: 12 + "years",
details: {Score: "650-720" , Name:"Test James"},
Score: "620-670",
Phone: "9292132019",
Mail: "Noe#temp2t.io",
State: "TX",
Opening: "11.11.2021",
Pf: "Priority urgent",
Flags: "In Progress",
Ls: "DavAff",
Company: "Mit",
Ras: "...",
}
)];
const columns = [
{
name: "details",
label: "Name",
options: {
customBodyRender: (value: any, tableMeta: any, updateValue: any) => {
return value?.Name;
},
sort: true,
filter: true,
setCellProps: () => ({
align: "center",
}),
setCellHeaderProps: (value: any) => ({
className: "centeredHeaderCell",
}),
},
},
{
name: "details",
label: "Score",
options: {
filter: true,
sort: true,
customBodyRender: (value: any, tableMeta: any, updateValue: any) => {
return value?.Score;
},
setCellProps: () => ({
align: "center",
}),
setCellHeaderProps: (value: any) => ({
className: "centeredHeaderCell",
}),
},
}
]
As you can see in the example I go to the details and display the Name, and in another column displays the Score.
Thanks in advance :-)
You can use it in a simple way. You just have to put the name of the column and the direction. Inside the table options
sortOrder: {
name: 'name',
direction: 'desc'
}
So your code would be something like this
const [data, setData] = useState([
{
ID: "A001",
Name: "Joe James",
Amount: "$300,000",
Purpose: "$220,000",
Tib: 12 + "years",
details: {Score: "620-670" , Name:"Joe James"},
Score: "620-670",
Phone: "9292132019",
Mail: "Nole#temp.io",
State: "TX",
Opening: "11.11.2021",
Pf: "Priority urgent",
Flags: "In Progress",
Ls: "DorAff",
Company: "Dit",
Ras: "...",
},
{
ID: "A001",
Name: "Joe James",
Amount: "$300,000",
Purpose: "$220,000",
Tib: 12 + "years",
details: {Score: "650-720" , Name:"Test James"},
Score: "620-670",
Phone: "9292132019",
Mail: "Noe#temp2t.io",
State: "TX",
Opening: "11.11.2021",
Pf: "Priority urgent",
Flags: "In Progress",
Ls: "DavAff",
Company: "Mit",
Ras: "...",
}
)];
const columns = [
{
name: "name",
label: "Name",
options: {
sort: true,
filter: true,
setCellProps: () => ({
align: "center",
}),
setCellHeaderProps: (value: any) => ({
className: "centeredHeaderCell",
}),
},
},
{
name: "score",
label: "Score",
options: {
filter: true,
sort: true,
setCellProps: () => ({
align: "center",
}),
setCellHeaderProps: (value: any) => ({
className: "centeredHeaderCell",
}),
},
}
];
const options = {
sortOrder: {
name: 'name',
direction: 'desc'
},
};
I was able to solve this, using the sortCompare function from the documentation!
https://www.npmjs.com/package/mui-datatables/v/3.3.1
You can add sortOrder in MUI Data Table Options
sortOrder: {
name: 'name',
direction: 'desc'
}
Example: https://github.com/gregnb/mui-datatables/blob/master/examples/customize-columns/index.js
sortOrder: Sets the column to sort by and its sort direction. To remove/reset sorting, input in an empty object. The object options are the column name and the direction: name: string, direction: enum('asc', 'desc')

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

Creating a new array from .map() items with certain value

In a React app, I have an array of key value pairs. Each pair corresponds to a checkbox, so when the checkbox is checked, the value of that key changes to either true or false. The data that i am pulling from is structured like:
filters: {
categories: [
{
name: "Books",
slug: "books",
selected: 0,
data: [
{ checked: false, value: "Fiction", label: "Fiction" },
{ checked: false, value: "NonFiction", label: "NonFiction" },
{ checked: false, value: "Biography", label: "Biography" },
],
},
{
name: "Movies",
slug: "movies",
selected: 0,
data: [
{ checked: false, value: "SciFi", label: "SciFi" },
{ checked: false, value: "Comedy", label: "Comedy" },
{ checked: false, value: "Romance", label: "Romance" },
],
},
{
name: "Music",
slug: "music",
selected: 0,
data: [
{ checked: false, value: "Pop", label: "Pop" },
{ checked: false, value: "Rock", label: "Rock" },
{ checked: false, value: "Alt", label: "Alt" },
],
},
],
selected: 0,
},
And I am displaying a simple list on the front-end like:
{state.theme.filters.categories.map((filter, id) => {
return (
<>
{filter.data.map((item) => {
return (
<p>{item.value}: {item.checked === true ? <span>True</span> : <span>False</span>}</p>
)
})}
</>
)
})}
What I am trying to do is create a new array that will automatically update and return only items that are checked true.
Is this something that is possible?
Yes, it is posible.
You need to filter the array.
{state.theme.filters.categories.map((filter, id) => {
return (
<>
{filter.data.filter(item => item.checked).map((item) => {
return (
<p>{item.value}: {item.checked === true ? <span>True</span> : <span>False</span>}</p>
)
})}
</>
)
})}
I think you simply want to check the checked value before returning, and not return otherwise. Something like this:
filter.data.map((item) => {
if (item.checked === true) {
return (
<p>{item.value}</p>
)
}
})

How to combine ant-design checkbox and table?

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>

Loop through an array of objects to update object values and append additional objects

I have a fields array with objects and I'm trying to loop this array:
fields: [
{
name: "seasonId",
type: "select",
label: "Season ID",
placeholder: "Select a season id...",
icon: "id",
value: "",
errors: "",
required: true,
disabled: true,
selectOptions: [],
},
{
name: "callTime",
type: "time",
label: "Scheduling Call Times",
placeholder: "Select a time...",
value: "",
errors: "",
required: true,
disabled: true,
},
];
To update its values AND append additional objects:
Incoming values:
"fieldValues": {
"callTimes": [
"5:45 pm",
"6:15 pm",
"6:30 pm",
"7:00 pm"
],
"selectedSeasonId": "20192020",
"seasonIds": [
"20192020",
"20202021",
"20212022",
]
}
Update field function:
const updateField = (currentField, fieldValues) => {
switch(currentField.name) {
case "seasonId":
return {
...currentField,
selectOptions: fieldValues.seasonIds,
value: fieldValues.selectedSeasonId,
disabled: false
};
case "callTime":
const callTimes = fieldValues.callTimes.map((value, key) => ({
...currentField,
name: key <= 0 ? "callTime" : `callTime-${Date.now()}`,
label: key <= 0 ? "Scheduling Call Times" : "",
value,
required: key <= 0,
disabled: false,
}));
return {
...callTimes
};
}
}
And then invoke the function above like so:
const updatedFields = fields.map(field => updateField(field, event));
However, I'm not getting the desired result.
Actual output:
[
'0': {
disabled: false
errors: ""
icon: "id"
label: "Season ID"
name: "seasonId"
placeholder: "Select a season id..."
required: true
selectOptions: ["20192020", "20202021", "20212022"]
type: "select"
value: "20192020"
},
'1': {
'0': {
disabled: false
errors: ""
label: "Scheduling Call Times"
name: "callTime"
placeholder: "Select a call time..."
required: true
style: {width: "100%"}
type: "time"
value: "5:45 pm"
},
'1': {
disabled: false
errors: ""
label: ""
name: "callTime-1565388886669"
placeholder: "Select a call time..."
required: false
style: {width: "100%"}
type: "time"
value: "6:15 pm"
},
'3': { ... },
'4': { ... }
}
];
Expected output:
[
'0': {
disabled: false
errors: ""
icon: "id"
label: "Season ID"
name: "seasonId"
placeholder: "Select a season id..."
required: true
selectOptions: ["20192020", "20202021", "20212022"]
type: "select"
value: "20192020"
},
'1': {
disabled: false
errors: ""
label: "Scheduling Call Times"
name: "callTime"
placeholder: "Select a call time..."
required: true
style: {width: "100%"}
type: "time"
value: "5:45 pm"
},
'2': {
disabled: false
errors: ""
label: ""
name: "callTime-1565388886669"
placeholder: "Select a call time..."
required: false
style: {width: "100%"}
type: "time"
value: "6:15 pm"
},
'3': { ... },
'4': { ... }
];
Any ideas on how I can update values and append additional objects to my fields array? The callTimes array of string values within the field object is dynamic (can contain 1 string or many), so I can't hard code anything.
const fields = [
{
name: "seasonId",
type: "select",
label: "Season ID",
placeholder: "Select a season id...",
icon: "id",
value: "",
errors: "",
required: true,
disabled: true,
selectOptions: [],
},
{
name: "callTime",
type: "time",
label: "Scheduling Call Times",
placeholder: "Select a time...",
value: "",
errors: "",
required: true,
disabled: true,
},
];
const fieldValues = {
"callTimes": [
"5:45 pm",
"6:15 pm",
"6:30 pm",
"7:00 pm"
],
"selectedSeasonId": "20192020",
"seasonIds": [
"20192020",
"20202021",
"20212022",
]
};
const updateField = (currentField, event) => {
switch(currentField.name) {
case "seasonId":
return {
...currentField,
selectOptions: fieldValues.seasonIds,
value: fieldValues.selectedSeasonId,
disabled: false
};
case "callTime":
const callTimes = fieldValues.callTimes.map((value, key) => ({
...currentField,
name: key <= 0 ? "callTime" : `callTime-${Date.now()}`,
label: key <= 0 ? "Scheduling Call Times" : "",
value,
required: key <= 0,
disabled: false,
}));
return {
...callTimes
};
}
};
const updatedFields = fields.map(field => updateField(field, event));
console.log(updatedFields);
Using reduce instead of map, I believe I am getting the right output:
const updateField = (result, currentField) => {
switch (currentField.name) {
case 'seasonId':
return [
...result,
{
...currentField,
selectOptions: fieldValues.seasonIds,
value: fieldValues.selectedSeasonId,
disabled: false
}
]
case 'callTime':
const callTimes = fieldValues.callTimes.map(...);
return [
...result,
...callTimes
]
}
}
const updatedFields = fields.reduce(updateField, [])
Since your callTime case was returning multiple objects in an array, map wouldn't work well in this case as you need to push/add these objects individually to the "final" array, hence this return:
case 'callTime':
const callTimes = fieldValues.callTimes.map(...);
return [
...result,
...callTimes
]
Also, your callTimes came out to be an array, and you tried to spread its items into an object:
case "callTime":
const callTimes = fieldValues.callTimes.map(...); // array
return {
...callTimes
};
This is why you were getting an unexpected/weird outcome.
Here's a demo with the fix:
Link
Since you asked in the comments how to pass fieldValues to the reducer function since they are being imported from another file, you can do the following:
const updateField = (result, currentField, fieldValues) => {...}
const updatedFields = fields.reduce(
(result, field) => updateField(result, field, fieldValues),
[]
)
Everything else stays the same.
Here's another demo:
Link

Categories