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

Google Dorking: Unlocking Hidden Search Capabilities & Insights

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

Wow you have been viewing my site since 20 seconds!

+
+