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
You can fix this issues by adding
PrimeReactProvider
inindex.jsx
index.jsx
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 theuseContext()
call.Reference: https://react.dev/reference/react/useContext
Sandbox: https://codesandbox.io/p/devbox/solitary-leaf-forked-7qnjdj
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