I created a Context API for menu bar and it is my first time using it, and that also I am using it with typescript which i started learning few days ago.
Context Creator and Provider Code in App.jsx
type MenuBar = {
menu: boolean
setMenu: any
}
function App() {
const MenuBarContext = React.createContext<Partial<MenuBar>>({})
const [menu, setMenu] = useState<boolean>(false)
return (
<MenuBarContext.Provider value={{ menu, setMenu }}>
<div className="h-full font-primary-400">
<Router>
<Navbar />
<Routes>
<Route path="/" element={<HomePage />} />
</Routes>
</Router>
</div>
</MenuBarContext.Provider>
)
}
Accesing using UseContext Hook in Navbar Component
const { menu, setMenu } = useContext(MenuBarContext)
I want to pass the state in the context API and access it in different components. But the accessing the context API using useContext hook gives error as -
Cannot find name 'MenuBarContext'.
Define the context in a separate file and import it where you need it.
MenuBarContext.ts:
import React from 'react';
// other imports...
const MenuBarContext = React.createContext<Partial<MenuBar>>({});
export default MenuBarContext;
Import it like so when you need to use MenuBarContext.Provider
or useContext(MenuBarContext)
:
import MenuBarContext from './MenuBarContext';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.