Created
June 30, 2021 16:44
-
-
Save kingisaac95/2487111efc72b17b840099cfb6594860 to your computer and use it in GitHub Desktop.
Tabs Component - React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Tabs.jsx | |
import PropTypes from 'prop-types'; | |
import { useState } from 'react'; | |
import styles from './Tabs.module.css'; | |
export const Tabs = ({ tabHeaders, children, defaultTab }) => { | |
const [currentTab, setCurrentTab] = useState(defaultTab.toLowerCase()); | |
const handleTabSelect = (tabHeader) => { | |
setCurrentTab(tabHeader.toLowerCase()); | |
}; | |
const tabContent = children.find( | |
(child) => child.props.name.toLowerCase() === currentTab | |
); | |
return ( | |
<section className={styles.spacing}> | |
<div className={styles.tabs}> | |
{tabHeaders.map((tabHeader) => ( | |
<div | |
key={tabHeader} | |
className={ | |
currentTab === tabHeader.toLowerCase() ? styles.active : '' | |
} | |
onClick={() => handleTabSelect(tabHeader)} | |
> | |
{tabHeader} | |
</div> | |
))} | |
</div> | |
{tabContent} | |
</section> | |
); | |
}; | |
Tabs.propTypes = { | |
children: PropTypes.oneOfType([ | |
PropTypes.arrayOf(PropTypes.node), | |
PropTypes.node, | |
]).isRequired, | |
defaultTab: PropTypes.string.isRequired, | |
tabHeaders: PropTypes.arrayOf(PropTypes.string).isRequired, | |
}; | |
export const Tab = ({ children }) => { | |
return <div className={styles.tabContent}>{children}</div>; | |
}; | |
Tab.propTypes = { | |
children: PropTypes.oneOfType([ | |
PropTypes.arrayOf(PropTypes.node), | |
PropTypes.node, | |
]).isRequired, | |
}; | |
// Tabs.module.css | |
.spacing { | |
margin-top: 50px; | |
} | |
.tabs { | |
display: flex; | |
justify-content: space-between; | |
} | |
.tabs > div { | |
flex-basis: 50%; | |
font-weight: 500; | |
font-size: 16px; | |
line-height: 19px; | |
text-align: center; | |
text-transform: capitalize; | |
color: var(--color-grey-3); | |
border-bottom: 2px solid var(--color-grey-3); | |
cursor: pointer; | |
padding: 12px; | |
} | |
.tabs > div.active { | |
color: var(--color-black); | |
border-bottom: 2px solid var(--color-black); | |
} | |
.tabContent { | |
margin-top: 10px; | |
} | |
// Usage | |
<Tabs tabHeaders={['activities', 'photos']} defaultTab="photos"> | |
<Tab name="activities"> | |
<div>Tab content - activities</div> | |
</Tab> | |
<Tab name="photos"> | |
<div>Tab content - photos</div> | |
</Tab> | |
</Tabs> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment