User Agents

Web browsers and everyday web tech, explained

Build a React Tabs Component: A Step-by-Step Guide

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Building a tabs component in React allows you to organize content into separate panes, reducing page clutter and improving user experience by letting users toggle between related views without reloading the page. This is achieved by using a piece of state to track the currently active tab and conditionally rendering the corresponding content based on that state.

What You'll Need

  • A functional React project (created via Vite, Create React App, or Next.js).
  • Basic knowledge of React hooks, specifically useState.
  • Basic CSS skills for styling the active and inactive states.
  • A modern web browser and a code editor like VS Code.

Step-by-Step

  1. Define Your Data Structure: Start by creating an array of objects that represents your tabs. Each object should contain a unique identifier (like an ID or index), a label for the tab button, and the content to be displayed. This makes your component scalable, allowing you to add new tabs by simply updating the data array rather than hard-coding HTML elements.
  2. Initialize State: Import { useState } from 'react'. Inside your component, create a state variable to keep track of the currently active tab. For example, const [activeTab, setActiveTab] = useState(0);. Setting the initial value to 0 ensures that the first tab is selected by default when the component mounts.
  3. Create the Tab Navigation: Use the .map() method to iterate over your tabs array. For each item, render a <button>. Assign an onClick handler to each button that calls setActiveTab(index). This updates the state whenever a user clicks a different tab.
  4. Apply Dynamic Styling: To provide visual feedback, apply a specific CSS class to the active tab. You can do this using a template literal: className={activeTab === index ? 'tab active' : 'tab'}. In your CSS, give the .active class a distinct background color or a bottom border to indicate it is selected.
  5. Implement Conditional Content Rendering: Below the navigation buttons, create a content area. Access the content of the currently active tab by referencing the state: <div className="tab-content">{tabs[activeTab].content}</div>. Because activeTab is a number representing the index, React will automatically re-render this section whenever the state changes.
  6. Optimize for Accessibility: To make the component accessible to screen readers, add ARIA roles. The container for the tabs should have role="tablist", each button should have role="tab" and aria-selected={activeTab === index}, and the content panel should have role="tabpanel".

Common Mistakes

  • Hard-coding Tabs: Manually writing out <button> elements for every tab makes the component difficult to maintain. Always use a data array and .map().
  • Using Strings as Keys without Uniqueness: If you use the tab label as a key in your map function and two tabs have the same name, React will throw a warning and may render content incorrectly. Use a unique ID or the array index.
  • Forgetting the Initial State: If you initialize state as null or undefined, the application will crash when trying to access tabs[activeTab].content. Always provide a default index.
  • Over-complicating State: Some developers try to use a complex object for state when a simple integer (the index) is sufficient for tracking the active tab.

Tips

  • Use Component Composition: For larger projects, split the logic into three components: Tabs (the wrapper), TabList (the navigation), and TabPanel (the content).
  • Add Transitions: Use CSS transitions or a library like Framer Motion to animate the content fade-in or the sliding indicator under the active tab for a more polished feel.
  • URL Integration: For tabs that should be shareable, use react-router-dom to sync the active tab with a URL query parameter (e.g., ?tab=profile) instead of local state.
  • Memoization: If the content within the tabs is computationally expensive to render, wrap the content panels in React.memo to prevent unnecessary re-renders of inactive tabs.

Troubleshooting

  • Content is not updating: Check if you are calling setActiveTab correctly. Ensure you are passing the index or ID and not the event object itself. If you use onClick={(e) => setActiveTab(index)}, it should work; if you use onClick={setActiveTab}, you are passing the event, which will break the index lookup.
  • Styles are not applying: Verify that your conditional class logic is correct. Use the browser inspector to see if the active class is actually being added to the DOM element when clicked.
  • Component crashes on load: Ensure your data array is defined before the component attempts to render tabs[activeTab]. If data is fetched from an API, add a loading state or a conditional check: {tabs && tabs[activeTab] && ...}.

Frequently Asked Questions

Can I use this for vertical tabs?

Yes. The logic remains identical. You only need to change the CSS of the tab list from display: flex; flex-direction: row; to flex-direction: column;.

How do I handle very large amounts of content in tabs?

Instead of rendering all content and hiding it with CSS, only render the active tab's content using the conditional rendering method described in the steps. This keeps the DOM lean.

Is it better to use a library like Material UI or Headless UI?

For simple projects, a custom component is better to avoid bundle bloat. For enterprise apps requiring complex accessibility (keyboard navigation, focus management), a library is recommended.

How can I make the tabs keyboard accessible?

Ensure you use <button> elements rather than <div>s, as buttons are natively focusable. You can also add a onKeyDown listener to allow users to switch tabs using the arrow keys.

Can I pass components as tab content?

Yes. In your data array, instead of a string for content, you can store a React component: content: <ProfileSettings />. React will render the component normally when that tab is selected.