Skip to content

Instantly share code, notes, and snippets.

@ever-dev
Last active September 23, 2020 19:10
Show Gist options
  • Save ever-dev/c9eeb399d2226f860aed5b53d7f08e9c to your computer and use it in GitHub Desktop.
Save ever-dev/c9eeb399d2226f860aed5b53d7f08e9c to your computer and use it in GitHub Desktop.
React Tab Component using emotion
/** @jsx jsx */
import { jsx, css } from '@emotion/core'
import { FunctionComponent, useState } from 'react'
import { Icon } from '~/components'
import PerfectScrollbar from 'react-perfect-scrollbar'
import 'react-perfect-scrollbar/dist/css/styles.css'
interface Tab {
title: string
Content: FunctionComponent<{}>
onClose?: () => any
}
interface TabsProps {
contents: Tab[]
onPlus?: () => any
}
export const Tabs: FunctionComponent<TabsProps> = ({ contents, onPlus }) => {
const [tabNumber, setTabNumber] = useState(0)
if (contents && !contents[tabNumber]) {
if (contents.length > 0) {
setTabNumber(contents.length - 1)
}
}
return (
<div css={[styles.container]}>
<PerfectScrollbar style={{ flex: 1 }}>
<div css={[styles.header]}>
{contents &&
contents.map((item, index) => (
<div
key={index}
css={[styles.tab, index === tabNumber && styles.active]}
onClick={() => {
setTabNumber(index)
}}
>
{item.title}
{item.onClose && (
<div css={styles.closeIcon}>
<Icon
color="#6d7d84"
icon="remove"
onClick={(e) => {
e.stopPropagation()
item.onClose()
}}
/>
</div>
)}
</div>
))}
{onPlus && (
<div css={styles.tab} data-test-id="plus-btn">
<Icon color="#6d7d84" icon="plus" onClick={onPlus} />
</div>
)}
<div css={[styles.tab, styles.rest]} />
</div>
</PerfectScrollbar>
{contents && contents[tabNumber] && (
<div css={[styles.content]}>{contents[tabNumber].Content({})}</div>
)}
</div>
)
}
const styles = {
container: css``,
header: css`
display: flex;
`,
tab: css`
border: none;
border-bottom: 1px solid #d2d7e0;
padding: 10px;
user-select: none;
color: #151f26;
display: flex;
align-items: center;
`,
active: css`
border: 1px solid #d2d7e0;
border-bottom: none;
`,
content: css`
border: 1px solid #d2d7e0;
border-top: none;
`,
rest: css`
flex-grow: 1;
padding: 0;
`,
closeIcon: css`
margin-left: 10px;
cursor: pointer;
`,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment