Skip to content

Commit c2765c3

Browse files
Convert useTheme to TS
1 parent e46c080 commit c2765c3

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/pages/useTheme.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ title: useTheme
44
date: "2019-01-07"
55
gist: https://gist.github.com/gragland/509efd16c695e7817eb70921c77c8a05
66
sandbox: https://codesandbox.io/s/15mko9187
7+
isMultilingual: true
78
links:
89
- url: https://medium.com/geckoboard-under-the-hood/how-we-made-our-product-more-personalized-with-css-variables-and-react-b29298fde608
910
name: CSS Variables and React
@@ -52,3 +53,49 @@ function useTheme(theme) {
5253
);
5354
}
5455
```
56+
57+
```typescript
58+
import { useLayoutEffect } from "react";
59+
import "./styles.scss"; // -> https://codesandbox.io/s/15mko9187
60+
61+
// Usage
62+
const theme = {
63+
"button-padding": "16px",
64+
"button-font-size": "14px",
65+
"button-border-radius": "4px",
66+
"button-border": "none",
67+
"button-color": "#FFF",
68+
"button-background": "#6772e5",
69+
"button-hover-border": "none",
70+
"button-hover-color": "#FFF",
71+
};
72+
73+
// This is type of "theme" object, kind of dynamic type
74+
interface Theme {
75+
[name: string]: string;
76+
}
77+
78+
function App() {
79+
useTheme(theme);
80+
81+
return (
82+
<div>
83+
<button className="button">Button</button>
84+
</div>
85+
);
86+
}
87+
88+
// Hook
89+
function useTheme(theme: Theme): void {
90+
useLayoutEffect(
91+
(): void => {
92+
// Iterate through each value in theme object
93+
for (const key in theme) {
94+
// Update css variables in document's root element
95+
document.documentElement.style.setProperty(`--${key}`, theme[key]);
96+
}
97+
},
98+
[theme] // Only call again if theme object reference changes
99+
);
100+
}
101+
```

0 commit comments

Comments
 (0)