Yonko
Yonko

Reputation: 33

How to make column cells collapsible in React

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>
}

Upvotes: 1

Views: 725

Answers (1)

Taghi Khavari
Taghi Khavari

Reputation: 6582

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.

Upvotes: 1

Related Questions