Created
September 13, 2021 11:36
-
-
Save maxmckenzie/26a92eeca6d51876687103c53b4730c5 to your computer and use it in GitHub Desktop.
Simple React + Typescript Tabs component
This file contains 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
import React, { useState } from 'react'; | |
interface Props { | |
activeTab: String, | |
children: any | |
} | |
interface TabProps { | |
title: String; | |
label: String; | |
onClick: (e: Event) => void; | |
activeTab: String; | |
} | |
const Tab = ({ title, label, onClick, activeTab }: TabProps) => ( | |
<li | |
onClick={onClick} | |
role="presentation" | |
class={`tab-pane ${activeTab === label ? 'active' : ''}`} | |
> | |
<a href="#" role="tab">{title}</a> | |
</li> | |
) | |
export function Tabs({ activeTab, children }: Props) { | |
const [active, setActive] = useState(activeTab); | |
const onClickTabItem = (label: String) => { | |
setActive(label) | |
}; | |
return ( | |
<div> | |
<ul role="tablist" class="tabs-nav"> | |
{children.map((child: { props: { label: String; title: String; }; }) => { | |
const { label, title } = child.props; | |
return ( | |
<Tab | |
activeTab={activeTab} | |
title={title} | |
key={label} | |
label={label} | |
onClick={() => onClickTabItem(label)} | |
/> | |
) | |
})} | |
</ul> | |
<div class="tab-content" role="tab-panel"> | |
{children.map((child: { props: { label: String; children: any; }; }) => { | |
if (child.props.label !== active) return; | |
return child.props.children; | |
})} | |
</div> | |
</div> | |
) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment