When formulating your question, please make sure to include a well-written code example.
However, here is the sample solution provided:
// index.js
import Tabs from "./tabs"
import "./style.css"
const App = () => {
return (
<Tabs>
<span title="Apple">Apple is red</span>
<span title="Banana">Banana is yellow</span>
</Tabs>
)
}
export default App
// tabs.js
import React, { useState } from 'react';
import TabTitle from './tabtitle';
const Tabs = ({ children }) => {
const [selectedTab, setSelectedTab] = useState(0);
return (
<div>
<ul className='tab-list'>
{children.map((item, index) => (
<TabTitle
key={index}
title={item.props.title}
index={index}
setSelectedTab={setSelectedTab}
selectedTab={selectedTab}
/>
))}
</ul>
{children[selectedTab]}
</div>
);
};
export default Tabs;
// tabtitle.js
import React, { useCallback } from 'react';
const TabTitle = ({ title, setSelectedTab, index, selectedTab }) => {
const onClick = useCallback(() => {
setSelectedTab(index);
}, [setSelectedTab, index]);
return (
<li className={`tab ${selectedTab === index ? 'active' : ''}`}>
<button onClick={onClick}>{title}</button>
</li>
);
};
export default TabTitle;
// style.css
.tab {
display: inline-block;
padding: 8px;
}
.active > button {
background-color: blue;
font-weight: bold;
}