'How to properly use useContext whit styled-components
I'm implementing a dark mode, but I did not get how to use theme inside my GlobalStyle, I'm trying to implement this since 4 days ago, I watched countless videos. I'm stuck at this error at the moment:
Uncaught ReferenceError: theme is not defined
GlobalStyle GlobalStyle.jsx:7
GlobalStyle.jsx
import { createGlobalStyle } from "styled-components";
export const GlobalStyle = createGlobalStyle`
body{
margin:0;
padding:0;
background-color: ${props => theme.colors.primary}; // error HERE !!!
color: ${props => theme.colors.text};
}
`;
App.jsx
import { useContext } from "react"
import { ThemeLocalContext, ThemeLocalProvider } from "./context/themeContext"
import { ThemeProvider } from "styled-components"
import {Paths} from "./pages/Paths/"
import { GlobalStyle } from "./styles/GlobalStyle/GlobalStyle"
function App() {
const theme = useContext(ThemeLocalContext);
console.log(theme) // this print my theme object
return (
<div>
<ThemeLocalProvider>
<>
<ThemeProvider theme={theme}>
<GlobalStyle/>
<Paths/>
</ThemeProvider>
</>
</ThemeLocalProvider>
</div>
)
}
export default App
ThemeContext.jsx
import React, { createContext, useState } from "react";
import { lightTheme } from "../styles/Theme/lightTheme";
import { darkTheme } from "../styles/Theme/darkTheme";
export const ThemeLocalContext = createContext(lightTheme);
export const ThemeLocalProvider = ({children}) => {
const [theme, setTheme] = useState(lightTheme);
const handleChange = (theme) => {
setTheme(theme.title === 'light' ? darkTheme : lightTheme);
}
return (
<ThemeLocalContext.Provider value={theme}>
{children}
</ThemeLocalContext.Provider>
)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
