Search code examples
javascripthtmlmdc-components

How to use MDC's tab bar?


I want to use this Tab system:

https://material-components.github.io/material-components-web-catalog/#/component/tabs

I read the HTML source code of the above link and implemented a tab bar.

However, how do I switch displayed contents using this tab bar? Do I need to write JavaScript?


Solution

  • Yes, it is a JavaScript library.... so you will need to import the JavaScript.

    Firstly you need to install the library, installation instructions can be found here.

    Next you can proceed to using the tab bar, following these instructions.

    Here's a quick working demo to show it's possible, (but I wouldn't recommend using this code)

    <!-- Required styles for MDC Web -->
    <link rel="stylesheet" href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css">
    
    <!-- Render tab barcomponent -->
    <div class="mdc-tab-bar" role="tablist">
      <div class="mdc-tab-scroller">
        <div class="mdc-tab-scroller__scroll-area">
          <div class="mdc-tab-scroller__scroll-content">
            <button class="mdc-tab mdc-tab--active" role="tab" aria-selected="true" tabindex="0">
              <span class="mdc-tab__content">
                <span class="mdc-tab__icon material-icons" aria-hidden="true">favorite</span>
              </span>
              <span class="mdc-tab-indicator mdc-tab-indicator--active">
                <span class="mdc-tab-indicator__content mdc-tab-indicator__content--underline"></span>
              </span>
              <span class="mdc-tab__ripple"></span>
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- Required MDC Web JavaScript library -->
    <script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script>