React createContext issue in Typescript? The SidebarProps represent the context’s state. Everything else, besides the reducer actions, can essentially be used as is.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | import React, { createContext, Dispatch, Reducer, useContext, useReducer } from 'react'; interface Actions { type: string; value: any; } interface SidebarProps { show: boolean; content: JSX.Element | null; } interface SidebarProviderProps { reducer: Reducer<SidebarProps, Actions>; initState: SidebarProps; } interface InitContextProps { state: SidebarProps; dispatch: Dispatch<Actions>; } export const SidebarContext = createContext({} as InitContextProps); export const SidebarProvider: React.FC<SidebarProviderProps> = ({ reducer, initState, children }) => { const [state, dispatch] = useReducer(reducer, initState); const value = { state, dispatch }; return ( <SidebarContext.Provider value={value}> {children} </SidebarContext.Provider> ); }; export const useSidebar = () => useContext(SidebarContext); const SidebarController: React.FC = ({ children }) => { const initState: SidebarProps = { show: false, content: null }; const reducer: Reducer<SidebarProps, Actions> = (state, action) => { switch (action.type) { case 'setShow': return { ...state, show: action.value }; case 'setContent': return { ...state, content: action.value }; default: return state; } }; return ( <SidebarProvider reducer={reducer} initState={initState}> {children} </SidebarProvider> ); }; export default SidebarController; |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.