Home > OS >  how use usecontext with TypeScript
how use usecontext with TypeScript

Time:09-04

I am new to TypeScript, I was trying to use context API but am getting a lot of errors, please can someone help to convert this Javascript code to TypeScript so I can know how it's been done

here the code

import React,{ createContext, useState, useContext } from "react";


const stateContext = createContext()

export const ContextProvider = ({children}) => {
    const [sidebar, setSidebar] = useState(false) 
    const [activeMenu, setActiveMenu] = useState(true)
    const [screenSize, setScreenSize] = useState(undefined)


    return(
        <stateContext.Provider value={{sidebar, setSidebar, screenSize, setScreenSize, activeMenu, setActiveMenu}}>
            {children}
        </stateContext.Provider>
    )
} 

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

CodePudding user response:

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

interface IStateContext {
  sidebar: boolean;
  setSidebar: Dispatch<SetStateAction<boolean>>;
  screenSize: number | undefined;
  setScreenSize: Dispatch<SetStateAction<number | undefined>>;
  activeMenu: boolean;
  setActiveMenu: Dispatch<SetStateAction<boolean>>;
}
const stateContext = createContext<IStateContext | null>(null);

interface IContextProviderProps {
  children: React.ReactNode;
}
export const ContextProvider = ({ children }: IContextProviderProps) => {
  const [sidebar, setSidebar] = useState<boolean>(false);
  const [activeMenu, setActiveMenu] = useState<boolean>(true);
  const [screenSize, setScreenSize] = useState<number | undefined>(undefined);

  return (
    <stateContext.Provider
      value={{
        sidebar,
        setSidebar,
        screenSize,
        setScreenSize,
        activeMenu,
        setActiveMenu
      }}
    >
      {children}
    </stateContext.Provider>
  );
};

export const useStateContext = () => useContext(stateContext);
  • Related