How To Create Bootstrap Tab Component In React

2
72
Tab Component in React.js Example

In regular bootstrap, building a tab component is a straightforward task. But creating inside React.js is a bit complex. We need to rely on the state to display active tabs.

Tab components allow you to break up complex user interfaces into more manageable subsections that a user can quickly switch between.

The navigation bar is not always the best solution. So, We will use Bootstrap 4 classes to display the Tab component.

Create Bootstrap Tab Component In React

We start our tutorial by installing React.js using create-react-app. Then we install Bootstrap 4 and use that Bootstrap-Navs css classes.

Step 1: Install React.js.

Type the following command. You do not need to install create-react-app if you have not installed it previously on your machine.

npm install -g create-react-app
create-react-app react-tab

Step 2: Install Bootstrap 4.

Type the following command.

npm install bootstrap --save

# or

yarn add bootstrap

Import the bootstrap.min.css file inside the App.js file.

// App.js

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

Step 3: Create three components.

Inside the src folder, create one folder called components.

Create three files inside the components folder.

  1. TabContent.js
  2. TabList.js
  3. Tab.js

Okay, now write the following code inside the TabContent.js file.

// TabContent.js

import React, { Component } from 'react';

import '../App.css';

export default class TabContent extends Component {
    render() {
        return (
            <div className="container up">
               <div className="tab-content">
                    Consequat occaecat ullamco amet non eiusmod nostrud dolore irure incididunt est duis anim sunt officia. Fugiat velit proident aliquip nisi incididunt nostrud exercitation proident est nisi. Irure magna elit commodo anim ex veniam culpa eiusmod id nostrud sit cupidatat in veniam ad. Eiusmod consequat eu adipisicing minim anim aliquip cupidatat culpa excepteur quis. Occaecat sit eu exercitation irure Lorem incididunt nostrud.
               </div>
                <div className="tab-content">
                     Ad pariatur nostrud pariatur exercitation ipsum ipsum culpa mollit commodo mollit ex. Aute sunt incididunt amet commodo est sint nisi deserunt pariatur do. Aliquip ex eiusmod voluptate exercitation cillum id incididunt elit sunt. Qui minim sit magna Lorem id et dolore velit Lorem amet exercitation duis deserunt. Anim id labore elit adipisicing ut in id occaecat pariatur ut ullamco ea tempor duis.
                </div>
                <div className="tab-content">
                     Est quis nulla laborum officia ad nisi ex nostrud culpa Lorem excepteur aliquip dolor aliqua irure ex. Nulla ut duis ipsum nisi elit fugiat commodo sunt reprehenderit laborum veniam eu veniam. Eiusmod minim exercitation fugiat irure ex labore incididunt do fugiat commodo aliquip sit id deserunt reprehenderit aliquip nostrud. Amet ex cupidatat excepteur aute veniam incididunt mollit cupidatat esse irure officia elit do ipsum ullamco Lorem. Ullamco ut ad minim do mollit labore ipsum laboris ipsum commodo sunt tempor enim incididunt. Commodo quis sunt dolore aliquip aute tempor irure magna enim minim reprehenderit. Ullamco consectetur culpa veniam sint cillum aliqua incididunt velit ullamco sunt ullamco quis quis commodo voluptate. Mollit nulla nostrud adipisicing aliqua cupidatat aliqua pariatur mollit voluptate voluptate consequat non.
                </div>
            </div>
        );
    }
}

Okay, this component is responsible for displaying the information after the user clicks on the appropriate tabs. Also, write the css code inside the App.css file.

// App.css

.up {
  margin-top: 50px
}

Now, import this file inside the src >> App.js file.

// App.js

import React, { Component } from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

import TabContent from './components/TabContent';

class App extends Component {
  render() {
    return (
      <TabContent />
    );
  }
}

export default App;

Save the file and start the React development server using the following command.

yarn start

Step 4: Build TabList.js component.

Now, this component is responsible for displaying the tab items. So, when we click any of the tab items, we will show the information related to that item. So, this TabList.js component expects an array of items. Now, we have already defined the items inside the TabContent.js file. So we need to set this TabList.js component as a parent component. So first, let us do that.

// TabContent.js

import React, { Component } from 'react';
import TabList from './TabList';

import '../App.css';

export default class TabContent extends Component {
    render() {
        return (
            <div className="container up">
                <TabList>
                    <div label="Sun" className="tab-content">
                        Consequat occaecat ullamco amet non eiusmod nostrud dolore irure incididunt est duis anim sunt officia. Fugiat velit proident aliquip nisi incididunt nostrud exercitation proident est nisi. Irure magna elit commodo anim ex veniam culpa eiusmod id nostrud sit cupidatat in veniam ad. Eiusmod consequat eu adipisicing minim anim aliquip cupidatat culpa excepteur quis. Occaecat sit eu exercitation irure Lorem incididunt nostrud.
                    </div>
                    <div label="Mon" className="tab-content">
                        Ad pariatur nostrud pariatur exercitation ipsum ipsum culpa mollit commodo mollit ex. Aute sunt incididunt amet commodo est sint nisi deserunt pariatur do. Aliquip ex eiusmod voluptate exercitation cillum id incididunt elit sunt. Qui minim sit magna Lorem id et dolore velit Lorem amet exercitation duis deserunt. Anim id labore elit adipisicing ut in id occaecat pariatur ut ullamco ea tempor duis.
                    </div>
                    <div label="Tue" className="tab-content">
                        Est quis nulla laborum officia ad nisi ex nostrud culpa Lorem excepteur aliquip dolor aliqua irure ex. Nulla ut duis ipsum nisi elit fugiat commodo sunt reprehenderit laborum veniam eu veniam. Eiusmod minim exercitation fugiat irure ex labore incididunt do fugiat commodo aliquip sit id deserunt reprehenderit aliquip nostrud. Amet ex cupidatat excepteur aute veniam incididunt mollit cupidatat esse irure officia elit do ipsum ullamco Lorem. Ullamco ut ad minim do mollit labore ipsum laboris ipsum commodo sunt tempor enim incididunt. Commodo quis sunt dolore aliquip aute tempor irure magna enim minim reprehenderit. Ullamco consectetur culpa veniam sint cillum aliqua incididunt velit ullamco sunt ullamco quis quis commodo voluptate. Mollit nulla nostrud adipisicing aliqua cupidatat aliqua pariatur mollit voluptate voluptate consequat non.
                    </div>
                </TabList>
            </div>
        );
    }
}

So, we have set the parent component to TabList, and all of the children are its content. Also, we have defined the label for every child components.

Now, add the following code inside the TabList.js file.

// TabList.js

import React, { Component } from 'react';
import PropTypes from 'prop-types';

import Tab from './Tab';

export default class TabList extends Component {
  static propTypes = {
    children: PropTypes.instanceOf(Array).isRequired,
  }

  constructor(props) {
    super(props);

    this.state = {
      activeTab: this.props.children[0].props.label,
    };
  }

  onClickTabItem = (tab) => {
    this.setState({ activeTab: tab });
  }

  render() {
    const { onClickTabItem, props: {children},state: {activeTab} } = this;

    return (
        <div>
            <nav>
            <div className="nav nav-pills">
                {children.map((child) => {
                const { label } = child.props;
    
                return (
                    <Tab
                    activeTab={activeTab}
                    key={label}
                    label={label}
                    onClick={onClickTabItem}
                    />
                );
                })}
            </div>
            </nav>
            <div className="tab-content">
            {children.map((child) => {
                if (child.props.label !== activeTab) return undefined;
                return child.props.children;
            })}
            </div>
      </div>
    );
  }
}

Here, all the content will be available as children because this component is the parent component. So we can access through this.props.children. By default active tab will be the first nav item, so set the state to activeTab as the first item.

If the user clicks another tab, then activeTab will be changed accordingly.

Now, here, we have compared the label values. We need to compare to show the information based on the active tab. So if the children and active Tab labels are the same, we display the data. Otherwise, we display undefined.

When the user clicks other tabs, this component rerenders and displays the data based on activeTab.

Finally, we need to write the following code inside the Tab.js file.

// Tab.js

import React, { Component } from 'react';
import PropTypes from 'prop-types';

export default class Tab extends Component {
  static propTypes = {
    activeTab: PropTypes.string.isRequired,
    label: PropTypes.string.isRequired,
    onClick: PropTypes.func.isRequired,
  };

  onClick = () => {
    const { label, onClick } = this.props;
    onClick(label);
  }

  render() {
    const { onClick, props: { activeTab, label }} = this;

    let className = 'nav-item nav-link';

    if (activeTab === label) {
      className += ' active';
    }

    return (
      <a
        className={className}
        onClick={onClick}
      >
        {label}
      </a>
    );
  }
}

The Tab.js component displays the tab’s name and adds the class if the tab is active. When clicked, the component will fire a handler that will let Tabs know which tab should be active. An according to the active tab, we display the information that is it. We have done the Bootstrap Tab Component in React.

Save the file, and you can see something like this.

How To Create Bootstrap Tab Component In React

We can also display the traditional way of tabs using this className inside TabList.js.

// TabList.js

<div className="nav nav-tabs">
     {children.map((child) => {
        const { label } = child.props;
    
         return (
               <Tab
                 activeTab={activeTab}
                 key={label}
                 label={label}
                 onClick={onClickTabItem}
                 />
           );
      })}
</div>

How To Create Tabs in React

That’s it.

2 Comments

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.