DEV Community

Utsav Mavani
Utsav Mavani

Posted on

Tab logic using ReactJS

how you can implement a simple tab logic using ReactJS. In this example, I'll use functional components and hooks. Let's create a component called Tabs:

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

const Tabs = () => {
  const tabs = ['Tab 1', 'Tab 2', 'Tab 3', 'Tab 4'];
  const [activeTab, setActiveTab] = useState(0);

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

  return (
    <div className="tabs-container">
      <div className="left-side">
        <h2>{tabs[activeTab]}</h2>
      </div>
      <div className="right-side">
        {tabs.map((tab, index) => (
          <div
            key={index}
            className={`tab ${activeTab === index ? 'active' : ''}`}
            onClick={() => handleTabClick(index)}
          >
            {tab}
          </div>
        ))}
      </div>
      <div className="content">
        {/* Render content based on active tab */}
        <div className={`tab-content ${activeTab === 0 ? 'active' : ''}`}>
          Content for Tab 1
        </div>
        <div className={`tab-content ${activeTab === 1 ? 'active' : ''}`}>
          Content for Tab 2
        </div>
        <div className={`tab-content ${activeTab === 2 ? 'active' : ''}`}>
          Content for Tab 3
        </div>
        <div className={`tab-content ${activeTab === 3 ? 'active' : ''}`}>
          Content for Tab 4
        </div>
      </div>
    </div>
  );
};

export default Tabs;

Enter fullscreen mode Exit fullscreen mode

In this example, we have a Tabs component with an array of tab titles (tabs) and a state variable (activeTab) to keep track of the currently active tab. The handleTabClick function is used to update the active tab when a tab is clicked.

Make sure to create a CSS file (e.g., Tabs.css) to style your tabs:

.tabs-container {
  display: flex;
  width: 100%;
}

.left-side {
  flex: 1;
}

.right-side {
  display: flex;
}

.tab {
  padding: 10px;
  cursor: pointer;
  border: 1px solid #ccc;
  margin-right: 5px;
}

.tab.active {
  background-color: #ddd;
}

.content {
  width: 100%;
  margin-top: 10px;
}

.tab-content {
  display: none;
}

.tab-content.active {
  display: block;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)