I read a lots article of writing a toggle to change the theme. For a beginner, this is entire too difficult to understand multiple files and code.
I'm going to show you guys a simple way to change the by using useState and styled-components 😛 😝
Here is my step:
Step 1 :
Install styled-components, we need this library.
npm install --save styled-components
Step 2:
Import these things, you will use useState later 😏
import { ThemeProvider } from "styled-components";
import { createGlobalStyle } from "styled-components";
import { useState } from "react";
Step 3:
Initialize the Dark and Light
Simply define our lovely variable 😛:
const [theme, setTheme] = useState("light");
const light = {
body: "#E2E2E2" // you can change to any color you like
};
const dark = {
body: "#363537" // you can change to any color you like
};
const GlobalStyle = createGlobalStyle`
body{
background: ${({ theme }) => theme.body};
}
`;
Step 4:
Return
import "./styles.css";
import { ThemeProvider } from "styled-components";
import { createGlobalStyle } from "styled-components";
import { useState } from "react";
export default function App() {
const [theme, setTheme] = useState("light");
const light = {
body: "#E2E2E2"
};
const dark = {
body: "#363537"
};
const GlobalStyle = createGlobalStyle`
body{
background: ${({ theme }) => theme.body};
}
`;
return (
<ThemeProvider theme={theme === "light" ? dark : light}>
<GlobalStyle />
<button
onClick={() => {
if (theme === "light") {
setTheme("dark");
} else {
setTheme("light");
}
}}
>
change
</button>
</ThemeProvider>
);
}
Top comments (0)