Skip to content

Tabs

Render tab buttons from data and show the content of the active tab, keeping the active index in state.

Stage 4intro1 min read

Problem Statement

Build a tabs component that takes a list of tabs as a prop and shows the content of the selected tab.

Functional Requirements

  1. Tab buttons: Render one button per item in tabsData, using its label.
  2. Default tab: The first tab is selected on load.
  3. Switch tabs: Clicking a button makes it the active tab and shows its content below the buttons.
  4. Active style: The selected button gets the active class.

Technical Constraints

  • Keep only the active index in state with useState(0).
  • Read the tab data from a local data.json file in App and pass it as the tabsData prop.

Key Concepts

  1. Component Structure
  • Main component Tabs receives tabsData as a prop
  • App component imports the tab data from a JSON file
  • Data structure uses an array of objects with label and content
  1. State Management
const [currentTab, setCurrentTab] = useState(0);
  • Uses useState hook to track active tab
  • Initially set to 0 (first tab)
  • currentTab stores the index of active tab
  1. Rendering Logic
  • Tabs Buttons:
{
  tabsData.map((item, index) => (
    <button
      className={`${currentTab === index ? "active" : ""}`}
      onClick={() => setCurrentTab(index)}
    >
      {item.label}
    </button>
  ));
}
  • Maps through tabsData to create buttons

  • Applies 'active' class when index matches currentTab

  • onClick updates currentTab state

  • Content Display:

<div className="tabs__content">{tabsData[currentTab]?.content}</div>
  • Shows content of currently selected tab using currentTab index
  • Optional chaining keeps an empty tabsData array from crashing the render

In this topic

Done with this topic?

How well do you know it?

PreviousAccordion