Create collapsible tabs in React Tab component

29 Aug 202315 minutes to read

You can achieve collapse and expand functionality in Tab by adding/removing a custom CSS class in the click event handler for each tab.

  • Define a CSS class to set the style property display as none. Here ‘collapse’ class is added to the content element for hiding it using created event.
  • Bind the selected event for Tab to collapse the initially selected Tab item and bind custom click handler for the Tab headers.
  • In the event handler, add and remove ‘collapse’ class to hide and show the corresponding Tab content.
import { useEffect, useRef, useState } from 'react';
import * as React from "react";
import * as ReactDOM from 'react-dom';
import { TabComponent, TabItemDirective, TabItemsDirective, SelectEventArgs } from '@syncfusion/ej2-react-navigations';
import { enableRipple } from '@syncfusion/ej2-base';

enableRipple(true);

const App = () => {
  const tabInstance = useRef(null);
  const [trgIndex, setrgIndex] = useState(0);
  let actLine;
  useEffect(() => {
    updateCollapseClass = updateCollapseClass;
  }, []);
  let updateCollapseClass = (index) => {
    // Custom classes are added/removed from tab content and active line element, when the same tab item again clicked
    const cntEle = tabInstance.current.element.querySelector("#e-content-element_" + index);
    actLine = tabInstance.current.element.querySelector('.e-indicator');
    if (cntEle.classList.contains('collapse')) {
      cntEle.classList.remove('collapse');
      actLine.classList.remove('collapse');
    } else {
      cntEle.classList.add('collapse');
      actLine.classList.add('collapse');
    }
  }

  const tabCreated = () => {
    // After tab created first tab content and active line are hidden by adding custom class
    actLine = tabInstance.current.element.querySelector('.e-indicator') as any;
    if (tabInstance.current.element.querySelector(".e-content-element_0") != null)
      (tabInstance.current.element.querySelector(".e-content-element_0") as any).classList.add('collapse');
    actLine.classList.add('collapse');
  }

  const tabSelected = (e) => {
    // If next tab item selected custom class is removed from content and active line element
    let cnttrgs = tabInstance.current.element.querySelectorAll('#element.e-tab > .e-content > .e-item');
    for (let i = 0; i < cnttrgs.length; i++) {
      cnttrgs[i].classList.remove('collapse');
    }
    if (actLine !== undefined) { actLine.classList.remove('collapse'); }
    setrgIndex(e.selectedIndex);
    e.selectedItem.onclick = (e) => {
      updateCollapseClass(trgIndex);
    };
  }

  const twitterContent = () => {
    return (<div>
      Twitter is an online social networking service that enables users to send and read short 140-character
      messages called "tweets". Registered users can read and post tweets, but those who are unregistered can only read
      them. Users access Twitter through the website interface, SMS or mobile device app Twitter Inc. is based in San
      Francisco and has more than 25 offices around the world. Twitter was created in March 2006 by Jack Dorsey,
      Evan Williams, Biz Stone, and Noah Glass and launched in July 2006. The service rapidly gained worldwide popularity,
      with more than 100 million users posting 340 million tweets a day in 2012.The service also handled 1.6 billion '
      search queries per day.
    </div>)
  }

  const faceBookContent = () => {
    return (<div>
      Facebook is an online social networking service headquartered in Menlo Park, California. Its website was
      launched on February 4, 2004, by Mark Zuckerberg with his Harvard College roommates and fellow students Eduardo
      Saverin, Andrew McCollum, Dustin Moskovitz and Chris Hughes.The founders had initially limited the website
      membership to Harvard students, but later expanded it to colleges in the Boston area, the Ivy League, and Stanford
      University. It gradually added support for students at various other universities and later to high-school students.
    </div>);
  }

  const WhatsAppContent = () => {
    return (
      <div>
        WhatsApp Messenger is a proprietary cross-platform instant messaging client for smartphones that operates
        under a subscription business model. It uses the Internet to send text messages, images, video, user location and
        audio media messages to other users using standard cellular mobile numbers. As of February 2016, WhatsApp had a user
        base of up to one billion,[10] making it the most globally popular messaging application. WhatsApp Inc., based in
        Mountain View, California, was acquired by Facebook Inc. on February 19, 2014, for approximately US$19.3 billion.
      </div>);
  }

  let headertext;
  headertext = [{ text: "Twitter" }, { text: "Facebook" }, { text: "WhatsApp" }];

  return (
    <TabComponent heightAdjustMode='Auto' className="e-background" id='element' ref={tabInstance} created={tabCreated} selected={tabSelected}>
      <TabItemsDirective>
        <TabItemDirective header={headertext[0]}
          content={twitterContent} />
        <TabItemDirective header={headertext[1]}
          content={faceBookContent} />
        <TabItemDirective header={headertext[2]}
          content={WhatsAppContent} />
      </TabItemsDirective>
    </TabComponent>
  );
}
const root = ReactDOM.createRoot(document.getElementById('element'));
root.render(<App />);
import { useEffect, useRef, useState } from 'react';
import * as React from "react";
import * as ReactDOM from 'react-dom';
import { TabComponent, TabItemDirective, TabItemsDirective, SelectEventArgs } from '@syncfusion/ej2-react-navigations';
import { enableRipple } from '@syncfusion/ej2-base';

enableRipple(true);

const App = () => {
  const tabInstance = useRef<TabComponent>(null);
  const [trgIndex, setrgIndex] = useState<number>(0);
  let actLine: HTMLElement;
  useEffect(() => {
    updateCollapseClass = updateCollapseClass;
  }, []);
  let updateCollapseClass = (index: number): void => {
    // Custom classes are added/removed from tab content and active line element, when the same tab item again clicked
    const cntEle: any = tabInstance.current.element.querySelector("#e-content-element_" + index);
    actLine = tabInstance.current.element.querySelector('.e-indicator') as any
    if (cntEle.classList.contains('collapse')) {
      cntEle.classList.remove('collapse');
      actLine.classList.remove('collapse');
    } else {
      cntEle.classList.add('collapse');
      actLine.classList.add('collapse');
    }
  }

  const tabCreated = (): void => {
    // After tab created first tab content and active line are hidden by adding custom class
    actLine = tabInstance.current.element.querySelector('.e-indicator') as any;
    if (tabInstance.current.element.querySelector(".e-content-element_0") != null)
      (tabInstance.current.element.querySelector(".e-content-element_0") as any).classList.add('collapse');
    actLine.classList.add('collapse');
  }

  const tabSelected = (e: SelectEventArgs): void => {
    // If next tab item selected custom class is removed from content and active line element
    let cnttrgs: NodeListOf<Element> = tabInstance.current.element.querySelectorAll('#element.e-tab > .e-content > .e-item');
    for (let i: number = 0; i < cnttrgs.length; i++) {
      cnttrgs[i].classList.remove('collapse');
    }
    if (actLine !== undefined) { actLine.classList.remove('collapse'); }
    setrgIndex(e.selectedIndex);
    e.selectedItem.onclick = (e: Event) => {
      updateCollapseClass(trgIndex);
    };
  }

  const twitterContent = () => {
    return (<div>
      Twitter is an online social networking service that enables users to send and read short 140-character
      messages called "tweets". Registered users can read and post tweets, but those who are unregistered can only read
      them. Users access Twitter through the website interface, SMS or mobile device app Twitter Inc. is based in San
      Francisco and has more than 25 offices around the world. Twitter was created in March 2006 by Jack Dorsey,
      Evan Williams, Biz Stone, and Noah Glass and launched in July 2006. The service rapidly gained worldwide popularity,
      with more than 100 million users posting 340 million tweets a day in 2012.The service also handled 1.6 billion '
      search queries per day.
    </div>)
  }

  const faceBookContent = () => {
    return (<div>
      Facebook is an online social networking service headquartered in Menlo Park, California. Its website was
      launched on February 4, 2004, by Mark Zuckerberg with his Harvard College roommates and fellow students Eduardo
      Saverin, Andrew McCollum, Dustin Moskovitz and Chris Hughes.The founders had initially limited the website
      membership to Harvard students, but later expanded it to colleges in the Boston area, the Ivy League, and Stanford
      University. It gradually added support for students at various other universities and later to high-school students.
    </div>);
  }

  const WhatsAppContent = () => {
    return (
      <div>
        WhatsApp Messenger is a proprietary cross-platform instant messaging client for smartphones that operates
        under a subscription business model. It uses the Internet to send text messages, images, video, user location and
        audio media messages to other users using standard cellular mobile numbers. As of February 2016, WhatsApp had a user
        base of up to one billion,[10] making it the most globally popular messaging application. WhatsApp Inc., based in
        Mountain View, California, was acquired by Facebook Inc. on February 19, 2014, for approximately US$19.3 billion.
      </div>);
  }

  let headertext: any;
  headertext = [{ text: "Twitter" }, { text: "Facebook" }, { text: "WhatsApp" }];

  return (
    <TabComponent heightAdjustMode='Auto' className="e-background" id='element' ref={tabInstance} created={tabCreated} selected={tabSelected}>
      <TabItemsDirective>
        <TabItemDirective header={headertext[0]}
          content={twitterContent} />
        <TabItemDirective header={headertext[1]}
          content={faceBookContent} />
        <TabItemDirective header={headertext[2]}
          content={WhatsAppContent} />
      </TabItemsDirective>
    </TabComponent>
  );
}
const root = ReactDOM.createRoot(document.getElementById('element'));
root.render(<App />);
#loader {
    color: #008cff;
    height: 40px;
    left: 45%;
    position: absolute;
    top: 45%;
    width: 30%;
}

.e-content .e-item {
    font-size: 12px;
    margin: 10px;
    text-align: justify;
}

.container {
    margin: 0 10px;
    min-width: 350px;
}

.info {
    margin: 10px;
    font-weight: bold;
}

.e-tab .e-content > .e-item.e-active.collapse { /* csslint allow: adjoining-classes */
    display: none;
}

.e-tab .e-tab-header .e-indicator.collapse { /* csslint allow: adjoining-classes */
    display: none;
}