I am fairly new to React but have a decent understanding of Javascript. I have a table where I am retrieving data about products from API. One of the fields(description of product) is very long and makes the table stretch the cells too tall. I need to make the cell in that field say 'description' by default but be able to open it to see the full description. Is there something I should be looking for ? I've not found alot of resources
export const Table = ({data}) => {
const columns = data[0] && Object.keys(data[0])
return <table cellPadding={0} cellSpacing={0}>
<thead>
<tr>{data[0] && columns.map((heading) => <th>{heading}</th>)}</tr>
</thead>
<tbody>
{data.map(row => <tr>
{
columns.map(column => <td>{row[column]}</td>)
}
</tr>)}
</tbody>
</table>
}
[{
"id": 1,
"dateCreated": "2022-01-31T16:25:09.882454",
"dateModified": "2022-01-31T16:25:09.882485",
"name": "Trendy Basketball Tank Top",
"sku": "STD-LDD-KJ",
"description": "Basketball Women Trendy eros lorem aliquam vitae eros ipsum ipsum ipsum eu dolor consecteur amet elit eu semper semper aliquam ac semper elit dolor ipsum vitae nec justo sit eros aliquam eu sed nec ipsum dolor semper aliquam aliquam nec vitae elit semper dapibus elit ac lorem dapibus aliquam semper adipiscing ipsum lorem aliquam nec semper eros elit eu",
"demographic": "Women",
"category": "Basketball",
"type": "Tank Top",
"releaseDate": "2040-10-28T10:43:36.989",
"primaryColorCode": "#f9845b",
"secondaryColorCode": "#f092b0",
"styleNumber": "scDZRSN",
"globalProductCode": "po-EDYGVSB",
"active": true,
"brand": "Adidas",
"imageSrc": "https://m.media-amazon.com/images/I/81WMOaI0zbL._AC_UX466_.jpg",
"material": "Nylon",
"price": 100,
"quantity": 3
}
CodePudding user response:
what you have to do is seperate the column into another component like this:
export const Table = ({ data }) => {
const columns = data[0] && Object.keys(data[0]);
return (
<table cellPadding={0} cellSpacing={0}>
<thead>
<tr>{data[0] && columns.map((heading) => <th>{heading}</th>)}</tr>
</thead>
<tbody>
{data.map((row) => (
<tr>
{columns.map((column, index) => {
if(column === "description") {
return <TableColumn key={index} text={row[column]} />
}
return <td>{row[column]}</td>
})}
</tr>
))}
</tbody>
</table>
);
};
const TableColumn = ({ text }) => {
const [open, setOpen] = React.useState(false);
const handleOpen = () => setOpen((v) => !v);
const thereshold = 20; // 20 charachtor, this is can be customized based on your needs
if (text.length > thereshold) {
return <td onClick={handleOpen}>{open ? text : "show description"}</td>;
}
return <td>{text}</td>;
};
this way you can handle the logic of showing the description and hiding it inside the newly created component.

