How to create Tabs in ReactJS ?

ReactJS is a popular JavaScript library for building user interfaces. It provides a component-based approach to web development, making it easier to create interactive and dynamic UI elements. Tabs are a common UI pattern used to organize and present content in a user-friendly manner. In this article, we will explore how to create a tab component in ReactJS.

Prerequisites

Before reading this article, you should have a basic understanding of ReactJS and its core concepts. Make sure you have Node.js and npm (Node Package Manager) installed on your machine.

Setting up a new React project

First, let's set up a new React project using Create React App, a tool that helps in creating a new React project with a basic project structure. Open your terminal and run the following command:

npx create-react-app tab-example
cd tab-example
npm start

Method 1: Using useState Hook

The simplest approach is to use the useState hook to manage the active tab state. This method is perfect for most tab implementations and follows React best practices.

Example

In the code below, we define a tabs array containing tab data, use useState to track the active tab, and render the tabs with click handlers. The active tab gets highlighted with an 'active' CSS class.

import React, { useState } from 'react';
import './Tabs.css'; // Import the CSS file

const Tabs = () => {
  const [activeTab, setActiveTab] = useState(0);

  // Define the tabs array within the component
  const tabs = [
    { title: 'Tab 1', content: 'Content for Tab 1' },
    { title: 'Tab 2', content: 'Content for Tab 2' },
    { title: 'Tab 3', content: 'Content for Tab 3' }
  ];

  const handleTabClick = (index) => {
    setActiveTab(index);
  };

  const renderTabs = () => {
    return tabs.map((tab, index) => (
      <div
        key={index}
        onClick={() => handleTabClick(index)}
        className={`tab-title ${activeTab === index ? 'active' : ''}`}
      >
        {tab.title}
      </div>
    ));
  };

  return (
    <div className="tabs-container">
      <div className="tabs-header">
        {renderTabs()}
      </div>
      <div className="tab-content">
        {tabs[activeTab]?.content}
      </div>
    </div>
  );
};

export default Tabs;

CSS Styling

Create a Tabs.css file to style the tab component:

.tabs-container {
  width: 100%;
  max-width: 600px;
  margin: 20px auto;
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
}

.tabs-header {
  display: flex;
  background-color: #f5f5f5;
}

.tab-title {
  padding: 12px 20px;
  cursor: pointer;
  background-color: #f5f5f5;
  border-right: 1px solid #ddd;
  transition: background-color 0.3s;
}

.tab-title:hover {
  background-color: #e9e9e9;
}

.tab-title.active {
  background-color: white;
  border-bottom: 2px solid #007bff;
  font-weight: bold;
}

.tab-content {
  padding: 20px;
  background-color: white;
  min-height: 200px;
}

Method 2: Using useReducer Hook

The useReducer hook is useful for more complex state logic. This approach is beneficial when you need to handle multiple actions or have complex tab behavior.

Example

Here we use a reducer function to manage state changes and dispatch actions to update the active tab:

import React, { useReducer } from 'react';
import './Tabs.css';

const reducer = (state, action) => {
  switch (action.type) {
    case 'SET_ACTIVE_TAB':
      return { ...state, activeTab: action.payload };
    case 'ADD_TAB':
      return { ...state, tabs: [...state.tabs, action.payload] };
    default:
      return state;
  }
};

const Tabs = () => {
  const initialState = {
    tabs: [
      { title: 'Tab 1', content: 'Content for Tab 1' },
      { title: 'Tab 2', content: 'Content for Tab 2' },
      { title: 'Tab 3', content: 'Content for Tab 3' }
    ],
    activeTab: 0
  };

  const [state, dispatch] = useReducer(reducer, initialState);

  const handleTabClick = (index) => {
    dispatch({ type: 'SET_ACTIVE_TAB', payload: index });
  };

  const renderTabs = () => {
    return state.tabs.map((tab, index) => (
      <div
        key={index}
        onClick={() => handleTabClick(index)}
        className={`tab-title ${state.activeTab === index ? 'active' : ''}`}
      >
        {tab.title}
      </div>
    ));
  };

  return (
    <div className="tabs-container">
      <div className="tabs-header">
        {renderTabs()}
      </div>
      <div className="tab-content">
        {state.tabs[state.activeTab]?.content}
      </div>
    </div>
  );
};

export default Tabs;

Method 3: Using useRef Hook

The useRef hook can store tab data that doesn't need to trigger re-renders. This approach is less common but can be useful when tab data is static.

Example

In this implementation, we use useRef to store static tab data and useState to manage the active tab state:

import React, { useRef, useState } from 'react';
import './Tabs.css';

const Tabs = () => {
  const tabsRef = useRef([
    { title: 'Tab 1', content: 'Content for Tab 1' },
    { title: 'Tab 2', content: 'Content for Tab 2' },
    { title: 'Tab 3', content: 'Content for Tab 3' }
  ]);
  
  const [activeTab, setActiveTab] = useState(0);

  const handleTabClick = (index) => {
    setActiveTab(index);
  };

  const renderTabs = () => {
    return tabsRef.current.map((tab, index) => (
      <div
        key={index}
        onClick={() => handleTabClick(index)}
        className={`tab-title ${activeTab === index ? 'active' : ''}`}
      >
        {tab.title}
      </div>
    ));
  };

  return (
    <div className="tabs-container">
      <div className="tabs-header">
        {renderTabs()}
      </div>
      <div className="tab-content">
        {tabsRef.current[activeTab]?.content}
      </div>
    </div>
  );
};

export default Tabs;

Comparison

Method Best For Complexity Performance
useState Simple tabs, most use cases Low Excellent
useReducer Complex tab logic, multiple actions Medium Good
useRef Static tab data Low Excellent

Usage in App Component

To use the Tabs component in your main App component:

import React from 'react';
import Tabs from './Tabs';
import './App.css';

function App() {
  return (
    <div className="App">
      <h1>React Tabs Example</h1>
      <Tabs />
    </div>
  );
}

export default App;

Conclusion

Creating tabs in ReactJS can be accomplished through multiple approaches. The useState hook is the most straightforward and recommended method for most cases, while useReducer provides better structure for complex tab behaviors. Choose the method that best fits your specific requirements and complexity level.

Updated on: 2026-03-15T23:19:01+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements