I have got a grid where in a column can have array of items. All I need is to implement a solution where in If that column has more than 1 items, need to display "Show more" and on click of it should show all the items(comma separated) and bring a "Show Less " link that would hide all items except the first one .Also when there is no data , just show "Not Available" for that column value. I am using react-table for grid purposes
I have tried the following : https://codesandbox.io/s/react-table-row-table-mpk9s
import * as React from "react";
import { render } from "react-dom";
import DataGrid from "./DataGrid";
import ShowMore from "./ShowMore";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
columns: [],
};
}
componentDidMount() {
this.getData();
this.getColumns();
}
showMoreUtility = arr => {
return <ShowMore value={arr} />;
};
getData = () => {
const data = [
{ firstName: "Jack", status: "Submitted", items: [1, 2, 3, 4] },
{ firstName: "Simon", status: "Pending", items: [1, 2] },
{ firstName: "Syls", status: "Pending", items: [1, 2] },
{ firstName: "Pete", status: "Approved", items: [] }
];
this.setState({ data });
};
getColumns = () => {
const columns = [
{
id: "1",
Header: "First Name",
accessor: "firstName"
},
{
id: "2",
Header: "Status",
accessor: "status"
},
{
id: "3",
Header: "Items",
accessor: arr => this.showMoreUtility(arr.items)
}
];
this.setState({ columns });
};
render() {
return (
<>
<DataGrid
data={this.state.data}
columns={this.state.columns}
/>
</>
);
}
}
Based on the code from the linked sandbox you could add a Cell
property to the items
column and pass the value to your ShowMore
component:
{
Header: "Items",
accessor: "items",
Cell: row => (
<ShowMore value={row.value} />
)
}
then in your ShowMore
component add || !value.length
to your condition in order to return Not Available
when there is no data
if (value === undefined || value === null || !value.length) {
return 'Not Available';
}
Also add a onClick
event to the div to update the value of isTruncated
and change the displayed data:
function handleClick() {
truncate(!isTruncated);
}
return (
<div onClick={handleClick}>
{
isTruncated
? <span>
{value[0]}
{value.length > 1 && ' Show more'}
</span>
: <span>
{value.join(',')}
{value.length > 1 && ' Show less'}
</span>
}
</div>
);
Working example: