Compound Components in React

Kunal Singh

Sep 9, 2024

import React, { useState } from 'react';

const Tabs = ({ children }) => {
const [activeIndex, setActiveIndex] = useState(0);

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

return (
<div>
<div className="tab-titles">
{React.Children.map(children, (child, index) => (
<button onClick={() => handleTabClick(index)}>
{child.props.label}
</button>
))}
</div>
<div className="tab-content">
{React.Children.toArray(children)[activeIndex]}
</div>
</div>
);
};

const Tab = ({ children }) => <div>{children}</div>;

// Usage
const App = () => (
<Tabs>
<Tab label="Tab 1">Content for Tab 1</Tab>
<Tab label="Tab 2">Content for Tab 2</Tab>
<Tab label="Tab 3">Content for Tab 3</Tab>
</Tabs>
);

export default App;
+

Check my latest Blog Post

How to Publish Your First npm Package: Creating Rainbow Highlight with Utilities

Read Now
Oh My Gawwdd!!!!!!!

Wow you have been viewing my site since 20 seconds!

+
+