Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to set the tab container's width to be the width of the widest tab? #549

Closed
ziyuang opened this issue Mar 24, 2024 · 1 comment
Closed

Comments

@ziyuang
Copy link

ziyuang commented Mar 24, 2024

This doesn't work as the container div's width is too small to hold the wide tab.

import { useRef, useEffect, useState } from "react";
import { Tab, Tabs, TabList, TabPanel } from "react-tabs";
import "react-tabs/style/react-tabs.css";

export const MyTab = () => {
  const containerRef = useRef<HTMLDivElement>(null);
  const [maxTabWidth, setMaxTabWidth] = useState(0);
  
  useEffect(() => {
    if (containerRef.current) {
      let maxWidth = 0;
      const tabElements =
        containerRef.current.querySelectorAll<HTMLElement>(".react-tabs__tab");
      tabElements.forEach((tab) => {
        const width = tab.offsetWidth;
        if (width > maxWidth) {
          maxWidth = width;
        }
      });
      setMaxTabWidth(maxWidth);
    }
  }, []);
  
  return (
    <div
      ref={containerRef}
      style={{ width: maxTabWidth }}
    >
      <Tabs>
        <TabList>
          <Tab>Tab 1</Tab>
          <Tab>Tab 2</Tab>
        </TabList>
          <TabPanel>
            Narrow tab
          </TabPanel>
        <TabPanel>
          {Array(100).join("a")}
        </TabPanel>
      </Tabs>
    </div>
  );
}

CodeSandbox

@ziyuang
Copy link
Author

ziyuang commented Mar 24, 2024

Looks like the class is .react-tabs__tab-panel. Although it doesn't fix my real case it fixes the simplified version in the sandbox.

@ziyuang ziyuang closed this as completed Mar 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant