1

I am using React, material-ui and material-table.

I have a closable tab panel. And when I change tabs I do not unmount the corresponding panel component. I just hide it with css. Which means that when I use my material-table component inside multiple tabs and I want to access the current table ref I just get the table ref which is inside of the recently opened tab panel.

How can I update the ref to correspond the current panels table when I cange the tab?

As I think I should update this ref on tab change event. But how can I do that? I use functional components and useRef.

I tried to use useCallback with no luck

This is my parent component:

const MainTabPanel = ({
  tabs,
  activeTab,
  setTabs,
  setActiveTab
}) => {

  const tableRef = useRef(null)

  const handleTabClose = (event, tabId) => {
    event.stopPropagation()
    const activeTabIndex = tabs.length > 1 ? tabs.length - 2 : 0
    setActiveTab(activeTabIndex)
    setTabs([
      ...tabs.filter(tab => tab.id !== tabId)
    ])
  }

  const handleTabChange = (event, newValue) => {
    setActiveTab(newValue)
  }

  return (
    <div>
      <TabsToolbar
        tabs={tabs}
        open={open}
        activeTab={activeTab}
        onTabClose={handleTabClose}
        onTabChange={handleTabChange}
      />
      <TableRefProvider value={tableRef}>
        {tabs.map(({ component: Component, id }, index) => (
            <Panel value={activeTab} index={index} key={id} padding={2}>
              <Component />
            </Panel>
          )
        )}
      </TableRefProvider>

    </div>
  )
}

export default MainTabPanel
Dito
  • 915
  • 2
  • 10
  • 26

1 Answers1

0

You can try to unmount the table and set the ref to the new table by using the given selected tab as key to the component.

This will force a rerender of the component on key/tab change and will reset the tableRef.

On a side note, why do you not unmount, but hide it with css?

Domino987
  • 8,475
  • 2
  • 15
  • 38