Reputation: 31
I'm trying to create a "Name" column in my material-table with concatenated firstname, lastname
from my array, but It only accepts one data per field.
Any suggestion or help to make it possible ?
const client = {
firstname: "Tracy",
lastname: "Santos",
address: {
address1: "Manila",
address2: "Philippines",
}
}
const columns = [
{ title: 'Name', field: 'client.firstname' + ' ' + 'client.lastname' },
{ title: 'Address', field: 'client.address.address1' + ' ' + 'client.address.address2' },
]
<MaterialTable
column={ columns }
data={ client }
/>
Upvotes: 3
Views: 6392
Reputation: 1
The above answers will only work if there is no search required in the material-table, if the search is required then you will have to add "customFilterAndSearch" to the answer as below-
const columns = [
{
title: 'Name',
render: client => `${client.firstname} ${client.lastname}`,
customFilterAndSearch: (term, client) => (client.firstname.toLowerCase() + ' ' + client.lastname.toLowerCase()).indexOf(term.toLowerCase()) !== -1
}
]
Upvotes: 0
Reputation: 429
An alternate approach that doesn't require modifying the data you pass to the table would be to use a custom render function for that field.
{
render: (client) => {
return `${client.firstName} ${client.lastName}`;
},
title: 'Client',
},
Upvotes: 4
Reputation: 2582
Your columns need to have a field
value that exists in the data object.
So, change your columns
object to be:
const columns = [
{ title: 'Name', field: 'fullName' },
{ title: 'Address', field: 'fullAddress' },
];
Once you have the columns, you need to modify the data you pass into the component.
const client = {
firstname: 'Tracy',
lastname: 'Santos',
address: {
address1: 'Manila',
address2: 'Philippines',
}
}
// Create the new object
const newData = {
fullName: `${client.firstname} ${client.lastname}`,
fullAddress: `${client.address.address1}, ${client.address.address2}`,
};
Then, you can pass the data to the table:
<MaterialTable columns={columns} data={newData} />
note
: I've used Template Literals here, because it's a little easier to read - but the code above is doing the following:
const newData = {
fullName: client.firstname + ' ' + client.lastname,
fullAddress: client.address.address1 + ', ' + client.address.address2,
};
Upvotes: 0