Aktzin
Aktzin

Reputation: 35

What is an easy way to create expandable rows on a table in React?

I tried looking this up but nothing but libraries came up that were kinda big for such a simple task. I was curious if any of you knew a simple way that onclick event for the table row, it will expand and display information about that row?

Upvotes: 0

Views: 3549

Answers (1)

Eugene
Eugene

Reputation: 10045

It's probably not explained in any libraries because of how simple it really is. Only show the information you're interested in if the row was toggled. In your data source, you need to have a flag for each expandable row.

const [rows, setRows] = useState([
  { ...rowContent, isExpanded: false }
]);

Afterwards in your UI that maps the rows into the content and renders them you need to display a UI element that will toggle the isExpanded state of your row or simply toggle it on click, the logic is the same.

<div className="row" onClick={() => {
  setRows(rows => {
    const newRows = [...rows];
    newRows[rowIndex].isExpanded = !newRows[rowIndex].isExpanded;
    return newRows;
  });
}>
  {...shortRowContent}
  {rows[rowIndex].isExpanded && (
    {...fullRowContent}
  )}
</div>

Upvotes: 2

Related Questions