Implement a Tabs component that switches content based on the active tab.

Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
import React, { useState } from 'react';

function Tabs({ children }) {
  const [activeTab, setActiveTab] = useState(children[0].props.label);

  const handleClick = (e, newActiveTab) => {
    e.preventDefault();
    setActiveTab(newActiveTab);
  };

  return (
    <div>
      <ul className="tabs">
        {children.map((child) => (
          <li 
            key={child.props.label} 
            className={child.props.label === activeTab ? 'active' : ''} 
            onClick={(e) => handleClick(e, child.props.label)}
          >
            {child.props.label}
          </li>
        ))}
      </ul>
      <div className="tab-content">
        {children.map((child) => {
          if (child.props.label !== activeTab) return undefined;
          return child.props.children;
        })}
      </div>
    </div>
  );
}

// Usage
function App() {
  return (
    <Tabs>
      <div label="Tab 1">Content 1</div>
      <div label="Tab 2">Content 2</div>
      <div label="Tab 3">Content 3</div>
    </Tabs>
  );
}