Search code examples
reactjsmaterial-uitabsheight

React MUI - Consistent Tab Content Height


I understand that ideally should be placed at the top of the page. However, Assume they are place in the middle of the page. When changing from a tab with a lot of content, to a tab with little content, the scrollable area disappears. Is there anyway to preserve the white space?

https://codesandbox.io/s/labtabs-material-demo-forked-y39i2g?file=/demo.tsx

Here is a code sandbox example.

Step 1 scroll down to tabs.

Step 2 scroll down tab 1 content( leave tabs visible)

Step 3 click tab 2 (Mouse no longer is hovering over tabs because vertical scroll content vanishes)

Edit: I am able to change my root div min height to whatever I need hard-coded. I feel like this hacky though and not dynamic to the tallest tab


Solution

  • You can set minHeight style to tab2 and tab3 to be the height of tab1 using useRef

    const tabRef = React.useRef<HTMLDivElement>(null)
    const [tabHeight, setTabHeight] = React.useState(0);
    React.useEffect(() => {
        setTabHeight(tabRef.current.clientHeight)
    }, [tabRef]);
    
    
    <TabPanel value="1" ref={tabRef}></TabPanel>
    <TabPanel value="2" sx={{ minHeight: tabHeight }}></TabPanel>
    <TabPanel value="3" sx={{ minHeight: tabHeight }}></TabPanel>
    

    Demo:
    https://codesandbox.io/s/labtabs-material-demo-forked-40kpwc?file=/demo.tsx