skip to Main Content

I am trying to use the changeTheme functionality as documented here on prime reacts website here

I have setup a very basic online sandbox here

    //CSS
    import "./App.css";
    import { useContext } from "react";
    import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
    import { PrimeReactContext } from "primereact/api";
    import LoginPage from "./components/Loginpage";

    //Prime React styles
    import "primeflex/primeflex.css";
    import "primereact/resources/themes/lara-light-indigo/theme.css";
    import "primereact/resources/primereact.min.css";
    import "primeicons/primeicons.css";

    function App() {
        const {changeTheme} = useContext(PrimeReactContext);
          return (
            <div className="App">
                <Router>
                <Routes>
                    <Route path="/" element={<LoginPage />} />
                </Routes>
              </Router>
           </div>
        );
    }

    export default App;

The line

const {changeTheme} = useContext(PrimeReactContext);

Throws the error
Uncaught TypeError: Cannot destructure property 'changeTheme' of 'useContext(...)' as it is undefined.

I have tried reaching out to the authors on their discord as well as searching here and elsewhere online.

2

Answers


  1. You can fix this issues by adding PrimeReactProvider in index.jsx

    index.jsx

    import { PrimeReactProvider } from "primereact/api";
    import { StrictMode } from "react";
    import { createRoot } from "react-dom/client";
    import App from "./App";
    
    const rootElement = document.getElementById("root");
    const root = createRoot(rootElement);
    
    root.render(
      <StrictMode>
        <PrimeReactProvider>
          <App />
        </PrimeReactProvider>
      </StrictMode>,
    );
    
    
    

    Note: useContext() call in a component is not affected by providers returned from the same component. The corresponding <Context.Provider> needs to be above the component doing the useContext() call.

    Reference: https://react.dev/reference/react/useContext

    Sandbox: https://codesandbox.io/p/devbox/solitary-leaf-forked-7qnjdj

    Login or Signup to reply.
  2. It seems like you’re trying to use the changeTheme functionality from PrimeReact, but you’re encountering an error where changeTheme is undefined when trying to destructure it from useContext(PrimeReactContext).

    First, ensure that you have properly wrapped your application with PrimeReactContextProvider. This provider should wrap around your entire application to make the changeTheme function available through the context

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search