priyanshu sinha
priyanshu sinha

Reputation: 625

React table V7 - detect Expanded Change

In React-table V6 we had a props - onExpandedChange, we could pass a func that would get executed when expansion was changed, how do we achieve same in react-table V7

Upvotes: 1

Views: 3283

Answers (2)

kaboom
kaboom

Reputation: 66

You can leverage the stateReducer option when creating the useTable instance. Something like this will take the expanded items from the prevState and remove them from the newState. There may be more elegant solutions but this worked for me in a pinch.

const stateReducer = useCallback((newState, action, prevState) => {
    // intercept expand toggles and collapse other expanded row(s)
    if (action.type === 'toggleRowExpanded') {
        const prevTokens = Object.keys(prevState.expanded);
        const newTokens = Object.keys(newState.expanded);

        if (newTokens.length > 1) {
            const nextExpanded = {};

            for (const t of newTokens) {
                if (!prevTokens.includes(t)) {
                    nextExpanded[t] = true;
                }
            }

            return { ...newState, expanded: nextExpanded };
        }
    }
    return newState;
}, []);

Then pass stateReducer into your useTable instance:

const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
    visibleColumns
} = useTable(
    {
        columns,
        data,
        stateReducer
    },
    useExpanded
);

Upvotes: 3

Sagar Pednekar
Sagar Pednekar

Reputation: 334

sinha, I didn't find any method to detect expand change but you can make use of the expanded object as it provides the status of expanded rows

const {
    state: { expanded }, // this will give you row/nested-row id with status
  } = useTable(
    {
      columns: userColumns,
      data,
    },
    useExpanded // Use the useExpanded plugin hook
  )

Row expanded

Example : Sandbox react table exapandables

Upvotes: 0

Related Questions