reactjsspfx

How to use context provider in webpart ts file


I am trying to use context provider in webpart ts file but i can't able to add context provider in it i don't have route files.First i add context provider in tsx file but the state variable gettting null value the data isn't passed in context.


Solution

  • AppContext.tsx:

    import React, { createContext, useContext, useState } from "react";
    
    const ThemeContext = createContext<any | null>(null);
    
    export const useAppContext = () => useContext(ThemeContext);
    
    export const ThemeProvider = ({ children }: any) => {
      const [state, setState] = useState({ theme: "red" });
    
      return (
        <ThemeContext.Provider
          value={{
            ...state,
            setTheme: (theme: any) => {
              setState({ ...state, theme });
            },
          }}
        >
          {children}
        </ThemeContext.Provider>
      );
    };
    

    App.tsx:

    <ThemeProvider>
         ....
    </ThemeProvider>
    

    some component:

    import React, { useState } from "react";
    import { useAppContext } from "./AppContext";
    
    
    function ...() {
      const { theme, setTheme } = useAppContext();
    
      return (
       ...
      );
    }
    export default Theme;