I am trying to render a table with dynamic content consisting of array of objects with Show More/ Show Less functionality.
While I am able to display the dynamic content, I am not able to bring in Show More/ Show less toggle. Basically Show More
should show up when the number of items are greater than 3 and it should append the rest of items to the first three items. Show Less
should be able to hide the items and show only first three
Help would be appreciated.
Sandbox: https://codesandbox.io/s/react-basic-class-component-3kpp5?file=/src/Table.js
Approach that I have tried
import * as React from "react";
class Table extends React.Component {
renderTableData = () => {
return this.props.data.map((item, index) => {
const { name, value } = item;
return (
<tr key={index}>
<td>{name}</td>
<td>{value}</td>
</tr>
);
});
};
renderTableHeader = () => {
let header = Object.keys(this.props.data[0]);
return header.map((key, index) => {
return <th key={index}>{key.toUpperCase()}</th>;
});
};
render() {
return (
<div>
<table>
<tbody>
<tr>{this.renderTableHeader()}</tr>
{this.renderTableData()}
</tbody>
</table>
</div>
);
}
}
export default Table;
From your code, I added a state named showLess to manage how the table should be displayed
import * as React from "react";
class Table extends React.Component {
constructor(props) {
super(props);
this.state = {
showLess: true
}
}
renderTableData = () => {
return this.props.data.map((item, index) => {
// If it's show less, then it should show only 3 rows, the others we will return null
if (this.state.showLess && index > 2) return null;
const { name, value } = item;
return (
<tr key={index}>
<td>{name}</td>
<td>{value}</td>
</tr>
);
});
};
renderTableHeader = () => {
let header = Object.keys(this.props.data[0]);
return header.map((key, index) => {
return <th key={index}>{key.toUpperCase()}</th>;
});
};
toggleShowLess = () => {
this.setState(prevState => ({
showLess: !prevState.showLess
}));
}
render() {
return (
<div>
<table>
<tbody>
<tr>{this.renderTableHeader()}</tr>
{this.renderTableData()}
<a href="#" onClick={this.toggleShowLess}>
{this.state.showLess ? 'Show More' : 'Show Less'}
</a>
</tbody>
</table>
</div>
);
}
}
export default Table;