Skip to content

Instantly share code, notes, and snippets.

@maxmckenzie
Created September 13, 2021 11:36
Show Gist options
  • Save maxmckenzie/26a92eeca6d51876687103c53b4730c5 to your computer and use it in GitHub Desktop.
Save maxmckenzie/26a92eeca6d51876687103c53b4730c5 to your computer and use it in GitHub Desktop.
Simple React + Typescript Tabs component
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