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.
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