I am trying to implement a show more/show less
functionality with respect to a table. Show More/ Show less
link should be visible only when there are more than 2 elements and show less should set it back to default number of items(i.e.2 in my case).Show More
should print rest of the items. I am using react-table for the same.There is a data grid component where I pass necessary props, and trying to implement this logic in the child.
I have tried the following. Can someone tell where I am going wrong?
Sandbox: https://codesandbox.io/s/react-table-row-table-ryiny?file=/src/index.js
import React from "react";
import ReactTable from "react-table";
import "react-table/react-table.css";
export default class DataGrid extends React.Component {
constructor(props) {
super(props);
this.state = {
showMore: false,
};
}
toggleState = () => {
this.setState(prevState => ({
showMore: !prevState.showMore
}), () => {
const subset: = this.state.showMore ? this.props.data : this.props.data.slice(0, 2);
});
}
renderTableData = () => {
const { data } = this.props;
const subset = this.state.showMore ? data : data.slice(0, 2);
return subset;
};
render() {
const { showMore } = this.state;
const { data,columns } = this.props;
const showLink = data.length > 2;
return (
<>
{showLink && (
<a onClick={this.toggleState}>
Show {showMore ? "Less" : "More")}
</a>
)}
<ReactTable
showPagination={false}
data={data}
columns={columns}
/>
</>
)
}
}
'columns' is in the props not the state and if that is the only functionality you need then remove the renderTableData function
Try this
...
export default class DataGrid extends React.Component {
constructor(props) {
super(props);
this.state = {
showMore: false,
};
}
toggleState = () => {
this.setState(prevState => ({
showMore: !prevState.showMore
}));
}
render() {
const { showMore } = this.state;
const { data, columns } = this.props;
const showLink = data.length > 2;
const subset = showMore ? data : data.slice(0, 2);
return (
<>
{showLink && (
<a onClick={this.toggleState}>
Show {showMore ? "Less" : "More"}
</a>
)}
<ReactTable
showPagination={false}
data={subset}
columns={columns}
/>
</>
)
}
}