Blog>
Snippets

Creating Expandable Rows

Showcase the process of making rows expandable to reveal child rows or additional information, focusing on the use of React state to manage the expanded or collapsed status of each row.
const [expandedRows, setExpandedRows] = React.useState({});
Defines a state to track which rows are expanded. It uses an object where each key is a row ID and the value is a boolean indicating if that row is expanded.
const toggleRow = (rowId) => {
  setExpandedRows(prevState => ({
    ...prevState,
    [rowId]: !prevState[rowId]
  }));
};
Function to toggle the expanded state of a row. It inversely sets the expanded state of given row ID.
const isRowExpanded = rowId => !!expandedRows[rowId];
Utility function to check if a row is expanded by checking the state for a given row ID.
{tableData.map((row) => (
  <React.Fragment key={row.id}>
    <tr onClick={() => toggleRow(row.id)}>
      <td>{row.name}</td>
      {/* Other td elements */}
    </tr>
    {isRowExpanded(row.id) && (
      <tr>
        <td colSpan="100%">{/* Expanded row content here */}</td>
      </tr>
    )}
  </React.Fragment>
))}
Renders each row with an onClick handler to toggle the expanded state. It conditionally renders the expanded content of a row based on its expanded state.