MenuContext.tsx36 lines · main
| 1 | 'use client' |
| 2 | |
| 3 | import React, { createContext, useContext } from 'react' |
| 4 | |
| 5 | interface ContextProps { |
| 6 | type: 'text' | 'pills' | 'border' |
| 7 | } |
| 8 | |
| 9 | interface Provider extends ContextProps { |
| 10 | children?: React.ReactNode |
| 11 | } |
| 12 | |
| 13 | // Make sure the shape of the default value passed to |
| 14 | // createContext matches the shape that the consumers expect! |
| 15 | const MenuContext = createContext<ContextProps>({ |
| 16 | type: 'text', |
| 17 | }) |
| 18 | |
| 19 | export const MenuContextProvider = (props: Provider) => { |
| 20 | const { type } = props |
| 21 | |
| 22 | const value = { |
| 23 | type: type, |
| 24 | } |
| 25 | |
| 26 | return <MenuContext.Provider value={value}>{props.children}</MenuContext.Provider> |
| 27 | } |
| 28 | |
| 29 | // context helper to avoid using a consumer component |
| 30 | export const useMenuContext = () => { |
| 31 | const context = useContext(MenuContext) |
| 32 | if (context === undefined) { |
| 33 | throw new Error(`MenuContext must be used within a MenuContextProvider.`) |
| 34 | } |
| 35 | return context |
| 36 | } |