React Context provider written in TypeScript
P粉714780768
P粉714780768 2024-03-28 22:28:44
0
1
432

I'm new to React context and TypeScript, and I'm trying to write a context to open and close the sidebar. This is my code

import React, { createContext, useContext, ReactNode, SetStateAction, Dispatch } from "react";



interface StateContextType {
    activeMenu: boolean
    setActiveMenu: Dispatch<SetStateAction<boolean>>;
}

export const StateContext = createContext<StateContextType>({
    activeMenu: true,
    setActiveMenu: () => {}
});



type ContextProviderProps = {
    children?: ReactNode
}

export const ContextProvider = ({ children }: ContextProviderProps) => {
    
    return (
        <StateContext.Provider
            value={{ activeMenu: true, setActiveMenu: () => { } }}
        >
            {children}
        </StateContext.Provider>
    )
}

export const useStateContext = () => useContext(StateContext)

When I try to use context in my application, the boolean "activeMenu" works fine, which means the sidebar displays based on its value. Because I set its default value to true the sidebar is shown and when I change it manually from the context provider it closes the sidebar but the problem here is that the setter function "setActiveMenu" does not work at all . As I said, I'm new to both react context and typescript, no error is showing up in my console, and I don't know why this is happening.

P粉714780768
P粉714780768

reply all(1)
P粉727531237

You are not storing your state anywhere and your context needs some support. try it

export const ContextProvider = ({ children }: ContextProviderProps) => {
    const [activeMenu, setActiveMenu] = useState(true);

    return (
        
            {children}
        
    )
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template