UNPKG

@ehsaneha/react-primitive-tab

Version:

A headless, type-safe, and hook-based tab primitive for React with full control over state management using react-observable-store.

43 lines (42 loc) 1.66 kB
var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; import React from "react"; import { useStore } from "@ehsaneha/react-observable-store"; export * from "./types"; export function useTab({ initIndex }) { const indexStore = useStore(initIndex); return { indexStore }; } export const TabContext = React.createContext({}); export function Tab(_a) { var { children } = _a, props = __rest(_a, ["children"]); const _tab = useTab(props); return React.createElement(TabContext.Provider, { value: _tab }, children); } export function useTabContext() { const context = React.useContext(TabContext); if (!context) { throw new Error("Tab Context not found!"); } return context; } export function useTabTrigger({ index }) { const { indexStore } = useTabContext(); const [isSelected, set] = indexStore.useState((s) => s === index); const _set = () => set(index); return [isSelected, _set]; } export function TabContent({ index, children, }) { const { indexStore } = useTabContext(); const [isSelected] = indexStore.useState((s) => s === index); return React.createElement(React.Fragment, null, isSelected && children); }