Skip to content

Instantly share code, notes, and snippets.

@daniele-zurico
Created January 11, 2019 14:12
Show Gist options
  • Select an option

  • Save daniele-zurico/0071cfa2667bfd0d20cad5044a84f617 to your computer and use it in GitHub Desktop.

Select an option

Save daniele-zurico/0071cfa2667bfd0d20cad5044a84f617 to your computer and use it in GitHub Desktop.

Revisions

  1. daniele-zurico created this gist Jan 11, 2019.
    36 changes: 36 additions & 0 deletions TabSwitcher-final.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    import React, { createContext, useState, useContext } from "react";

    const context = createContext({
    activeTabId: "a",
    changeTab: (id: string) => {}
    });

    const Tab = ({ id, children }: any) => {
    const tab = useContext(context);
    return <div onClick={() => tab.changeTab(id)}>{children}</div>;
    };

    const TabPanel = ({ whenActive, children }: any) => {
    const tab = useContext(context);
    return tab.activeTabId === whenActive ? children : null;
    };

    const TabSwitcher = ({ children }: any) => {
    const [activeTabId, setActiveTab] = useState<string>("a");
    const changeTab = (newTabId: any) => {
    setActiveTab(newTabId);
    };

    return (
    <context.Provider
    value={{
    activeTabId: activeTabId,
    changeTab: changeTab
    }}
    >
    {children}
    </context.Provider>
    );
    };
    export default TabSwitcher;
    export { Tab, TabPanel };