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
- Tab buttons: Render one button per item in
tabsData, using itslabel. - Default tab: The first tab is selected on load.
- Switch tabs: Clicking a button makes it the active tab and shows its
contentbelow the buttons. - Active style: The selected button gets the
activeclass.
Technical Constraints
- Keep only the active index in state with
useState(0). - Read the tab data from a local
data.jsonfile inAppand pass it as thetabsDataprop.
Key Concepts
- Component Structure
- Main component
TabsreceivestabsDataas a prop Appcomponent imports the tab data from a JSON file- Data structure uses an array of objects with
labelandcontent
- State Management
const [currentTab, setCurrentTab] = useState(0);- Uses
useStatehook to track active tab - Initially set to 0 (first tab)
currentTabstores the index of active tab
- 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
tabsDataarray from crashing the render