reactjsdatatablereact-table

Expand only one row at a time for React-DataTable component


I'm working with React DataTable react-data-table-component and I need to have an expandable table. In order to make the table expandable I have set expandableRows as true and I have also provided expandableRowsComponent. With the default react data-table implementation I can expand all the available rows in the table simultaneously. However, I would like to expand only 1 row at a time. So if I try to expand another row the already expanded row should collapse. How can I achieve this?

I also tried to use onRowExpandToggled. When I click a row to expand it returns the row that I expanded and value true. When the row is collapsed it returns false. I believe that I need to use this function to auto collapse the expanded rows but not sure how?


Solution

  • You can do this by leveraging on one more prop, the expandableRowExpanded which tracks the current row that is expanded. It takes a callback that you can use to compare to a state that you set in the onRowExpandToggled prop.

              const [currentRow, setCurrentRow] = useState(null);
    
    
              <DataTable
                expandableRows
                expandableRowExpanded={(row) => (row === currentRow)}
                expandOnRowClicked
                onRowClicked={(row) => setCurrentRow(row)}
                expandableRowsComponent={<ExpandableTable />}
                onRowExpandToggled={(bool, row) => setCurrentRow(row)}
                data={filteredData}
             />