Skip to content

Instantly share code, notes, and snippets.

@kaung8khant
Last active September 9, 2020 21:10
Show Gist options
  • Save kaung8khant/a00923525912f8859d3b66daf7c20784 to your computer and use it in GitHub Desktop.
Save kaung8khant/a00923525912f8859d3b66daf7c20784 to your computer and use it in GitHub Desktop.
useContext (React Hook)
import React, { useContext, useState } from "react";
import Tab from "./Tab";
import { MyContext } from "../MyContext";
const HomeScreen = () => {
const [tab, setTab] = useState(0);
const value = { tab, setTab };
return (
<MyContext.Provider value={value}>
<Tab />
</MyContext.Provider>
);
};
export default HomeScreen;
import React from "react";
export const MyContext = React.createContext({
tab: 0,
setTab: () => {},
});
import React, { useContext } from "react";
import { MyContext } from "../MyContext";
const Tab = () => {
const { tab, setTab } = useContext(MyContext);
return (
<ul>
<li onClick={() => setTab(0)}>tab1 {tab === 0 ? "active" : ""}</li>
<li onClick={() => setTab(1)}>tab2 {tab === 1 ? "active" : ""}</li>
</ul>
);
};
export default Tab;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment