Reactjs-tables. How to join multiple values into 1 cell? - reactjs

I am using react-table but I have 2 values that I want to join into one cell. Does anyone know how to do this?
Say I have this sample code, right now it has "name" which as the first and last name combined.
What happens if in my db I have it separate by first name and last. How could I join them together in the ui here(I know I could do this at the db level but this just an example)
import ReactTable from 'react-table'
render() {
const data = [{
name: 'Tanner Linsley',
age: 26,
friend: {
name: 'Jason Maurer',
age: 23,
}
},{
...
}]
const columns = [{
Header: 'Name',
accessor: 'name' // String-based value accessors!
}, {
Header: 'Age',
accessor: 'age',
Cell: props => <span className='number'>{props.value}</span> // Custom cell components!
}, {
id: 'friendName', // Required because our accessor is not a string
Header: 'Friend Name',
accessor: d => d.friend.name // Custom value accessors!
}, {
Header: props => <span>Friend Age</span>, // Custom header components!
accessor: 'friend.age'
}]
<ReactTable
data={data}
columns={columns}
/>
}

would this work?
const columns = [
{
Header: 'Full Name',
accessor: d => `${d.firstName} ${d.lastName}`
}
]

In case you want to sort by one of the values
{
Header: "Price",
accessor : "unit_price", // matters for grouping and sorting
Cell : props => <span>
{props.original.currency} {Numeral(props.original.unit_price).format('0,0.00')}
</span>
},

Related

How to sort 'react-data-table-component' by column number

I am using 'react-data-table-component' in React JS.
Following is my sample structure:
import DataTable from "react-data-table-component";
const data = myData;
const columns = [
{
name: 'Date',
selector: 'dateOfAction',
cell: row => <div>{moment(row.dateOfAction).format("MM-DD-YYYY A")}</div>,
sortable: true,
},
{
name: 'History Date',
selector: 'dateOfAction',
cell: row => <div>{moment(row.dateOfAction).format("YYYY-MM-DD HH:mm:ss")}</div>,
sortable: true,
}
];
<DataTable
columns={columns}
data={data}
defaultSortField="dateOfAction"
pagination
striped
defaultSortAsc={false}
/>
Here, Both columns have same selector.
And, I am able to sort data by first column i.e 'Date' but I want to sort table data by last column i.e 'History Date'.
How should I sort data by last column?
Thanks!
You can pass the defaultSortFieldId prop in the DataTable component. According to the documentation:
The defaultSortFieldId sets the a column to be pre sorted and
corresponds to the a column definition id
This means that you will need to provide an unique id for each column and then pass the id you want to use to the defaultSortFieldId:
const columns = [
{
id: 'date',
name: 'Date',
selector: 'dateOfAction',
cell: row => <div>{moment(row.dateOfAction).format("MM-DD-YYYY A")}</div>,
sortable: true,
},
{
id: 'historyDate',
name: 'History Date',
selector: 'dateOfAction',
cell: row => <div>{moment(row.dateOfAction).format("YYYY-MM-DD HH:mm:ss")}</div>,
sortable: true,
}
];
<DataTable
columns={columns}
data={data}
defaultSortFieldId="historyDate"
pagination
striped
defaultSortAsc={false}
/>

React table can't filtering when change data by 'Cell' option

I have columns array:
const columns = useMemo(
() => [
{
Header: 'User',
sortType: 'basic',
accessor: row => row,
Cell: ({ row }) => (
<div>
<img src={row.original.user.image}
/>
{row.original.user.name}
</div>
),
},
{
Header: 'Description',
accessor: 'description',
sortType: 'basic',
Cell: ({ cell: { value } }) => shortText(value),
},
{
Header: 'Created',
accessor: 'createdAt',
sortType: 'basic',
Cell: ({ cell: { value } }) =>
moment(value).format('DD-MM-YYYY HH:mm'),
},
],
[],
)
Filter not working for User and Created column. In table I change data by Cell function and changing data is render inside table, but filterGobal method filtering by data. E.g: inside table I have fromat data: 11-11-2021 15-45, but in data (from backend) I have "2021-11-11T15:44:44.787Z"
I thing I have this same problem with User column. In table I have only image and name user. But in data I have object:
user: {
id: 1,
name: "Jack",
age: 18,
}
How I can using globalFilter wit Cell method?
I found resolve, I just added accessor e.g:
{
Header: 'Created',
sortType: 'basic',
accessor: d => moment(d.createdAt).format('DD-MM-YYYY HH:mm'),
},
and for User column:
{
Header: 'User',
sortType: 'basic',
accessor: row => row.user.name,
Cell: ({ row }) => (
<div>
<img src={row.original.user.image}
/>
{row.original.user.name}
</div>
),
},
Now react-table filters by user.name parameter. If you need add age to
column, then you must add to accessor:
accessor: row => `${row.user.name} ${row.user.age}`,

How do I access this.state in my column for react-table

I want to have a toggle functionality in my react-table component
my columns is set like
const columns = [
{
Header: 'ID',
accessor : d => { return <Link to={"receipts/" + d.id}> {d.unique_id} </Link> },
},
{
Header: 'Student',
accessor: 'name'
},
{
Header: 'Paid Amount',
accessor: 'paid_amount',
},
{
id: 'is_paid',
Header: 'Paid?',
accessor: d => {
console.log(d);
return <Form.Check id={d.id} type='switch' checked={d.is_paid} onChange={this.handleToggle.bind(this)}/>
}
},
];
and my handleToggle is simply making an API call to update this row
But I'm getting
TypeError: Cannot read property 'handleToggle' of undefined
It seems like I'm not getting the this in my columns. How do I access this?
Have a look at this example https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/editable-data, it can be helpful in passing your own props to table and then using them in cell.

react-table render component inside data

I'm attempting to add a component inside the data using react-table package (https://www.npmjs.com/package/react-table#example)
Using the example from the package readme, I'm trying to use a fancy component to add an image to a cell:
using ** to jump out in the code...
I have also tried:
imageUrl:{<PlaceholderImage width={60} textColor="#fff" text="Image"/>}
example:
import ReactTable from 'react-table'
import 'react-table/react-table.css'
**import { PlaceholderImage } from 'react-placeholder-image'**
render() {
const data = [{
name: 'Tanner Linsley',
age: 26,
**imageUrl:<PlaceholderImage width={60} textColor="#fff" text="Image"/>,**
friend: {
name: 'Jason Maurer',
age: 23,
}
},{
...
}]
const columns = [{
Header: 'Name',
accessor: 'name' // String-based value accessors!
}, {
Header: 'Age',
accessor: 'age',
Cell: props => <span className='number'>{props.value}</span> // Custom cell components!
}, {
Header: ' ',
accessor: 'imageUrl', // String-based value accessors!
maxWidth: 70,
minWidth:70,
},{
id: 'friendName', // Required because our accessor is not a string
Header: 'Friend Name',
accessor: d => d.friend.name // Custom value accessors!
}, {
Header: props => <span>Friend Age</span>, // Custom header components!
accessor: 'friend.age'
}]
return <ReactTable
data={data}
columns={columns}
/>
}
You're passing a react component to a data field that expects a string. Try customising your cell via Cell props:
const columns = [
{
Header: "Image",
accessor: "imageUrl",
maxWidth: 70,
minWidth: 70,
Cell: props => <PlaceholderImage width={60} textColor="#fff" text="Image" />
}
];
In addition to #Clarity's answer, there's also a possibility to access the cell's value at the Cell's property level:
const columns = [
{
Header: "Image",
accessor: "imageUrl",
maxWidth: 70,
minWidth: 70,
Cell: ({ cell: { value } }) => (
<img
src={value}
width={60}
/>
)
}
];

react-table iterating over object array to print values in a column

I am using react-table to generate tables(https://react-table.js.org/#/story/readme). I have a state defined as following:
this.state = {
sampleTable:[
{author: 'Mac', books: [{title:'One', price: 20}, {title:'Two', price: 20}]},
{author: 'Rick', books: [{title:'Three', price: 20}, {title:'Four', price: 20}]}
],
sampleTableColumns:[
{Header: 'Author', accessor: 'author'},
{Header: 'Books', accessor: 'books.title'},
],
};
And I am trying to make table as following:
<ReactTable
className="-highlight"
data={this.state.sampleTable}
columns={this.state.sampleTableColumns}
defaultPageSize={10}
/>
However in the books column I see nothing. I am not sure how am I supposed to iterate over books array so that I can print say book titles in books column?
I had to write my accessor like following:
sampleTableColumns:[
{
Header: 'Author',
accessor: 'author',
},
{
Header: 'Books',
id:'books',
accessor: data => {
let output = [];
_.map(data.books, book => {
output.push(book.title);
});
return output.join(', ');
},
},
],
It's simple without using any dependencies like lodash...
You just need to use React-table Cell attribute
sampleTableColumns:[
{
Header: 'Author',
accessor: 'author',
},
{
Header: 'Books',
accessor: 'books',
Cell: (props) => {
const { sampleTable} = props.original;
return (
{ sampleTable.books.map( (book) =>(<h4>{book.title}</h4>)) }
);
},
},],
I believe Shivam Modi answered it. Using TypeScript his solution could be rendered something like (using built-in row selector):
{
Header: "Books",
accessor: "books",
Cell: ({ row }) => {
return (
row.original.books
.map((book: Book) => (
<div key={book.id}>
<h4>{book.name}</h4>
</div>
))
);
},
},
Your books data is an array and I don't believe react-table knows how to render those by default. You can instead supply your own render function in the sampleTableColumns for that cell, which would look something like:
sampleTableColumns:[
{Header: 'Author', accessor: 'author'},
{
Header: 'Books',
accessor: 'books'
render: (rowInfo) => {
return (
<span>
{rowInfo.value.map(book => (<span>{book.title}</span>))}
</span>
},
},
],
Well, I am too late for the party but all above doesn't work for me and I tried to use ES6 syntax. I have requested data in array, so here we go (I renamed variables):
export const returnPreparedField = (array) => {
const newArray = [];
for (let arrayValue of array) {
const newElement = {
id: "element",
header: element,
accessor: data => data.element.find(elementToFind => (elementToFind.name === element))?.value,
show: true,
width: 100
};
newArray.push(newElement);
}
return newArray;
};

Resources