Provides theme context and hooks. Supports theme switching via CSS custom properties.
The following example uses TypeScript.
- You only want to create a single theme context and reuse it throughout your application.
- You can create as many themes as you want, so long as they implement the same interface.
At its simplest, a theme can store colors:
export default interface Theme {
errorColor: string
anotherColor: string
}
Here's an example of a theme using this color:
import Theme from 'models/Theme'
const colors = {
scarlet: '#ff2400',
white: 'white',
}
const myTheme: Theme = {
errorColor: colors.scarlet,
anotherColor: colors.white,
}
export default myTheme
You might also want to base a color off of another:
class MyTheme implements Theme {
public errorColor = colors.scarlet
public get anotherColor() {
return darken(this.errorColor, 0.2)
}
}
export default new MyTheme()
Here's a contrived example of setting up an app with a couple of inline themes and creating a button to switch to the 2nd one.
import ThemeContext from 'react-theme-context'
const defaultTheme = { primaryColor: 'red' }
export default new ThemeContext(defaultTheme)
import React, { FC } from 'react'
import themeContext from './themeContext'
const App: FC = () => {
themeContext.useLayoutEffect()
const [theme, setTheme] = themeContext.use()
return (
<div style={`background: ${themeContext.prop('primaryColor')}`}>
<button
onClick={() => {
setTheme({ primaryColor: 'blue' })
}}
>
{theme.primaryColor}
</button>
</div>
)
}
export default App
import React from 'react'
import ReactDOM from 'react-dom'
import themeContext from './themeContext'
import App from './App'
const renderApp = () =>
ReactDOM.render(
<themeContext.Provider>
<App />
</themeContext.Provider>,
document.getElementById('root'),
)
renderApp()
See: React Docs | Context Provider
Converts property
into
CSS custom property
syntax. In TypeScript, it also prevents you from using a theme property that is
not defined.
themeContext.prop('primaryColor')
// 'var(--primary-color)'
Returns: [T, Dispatch<SetStateAction<T>>]
Sets theme properties as
CSS custom properties on
the provided options.element
or the root documentElement
by default. If the
theme is updated, these props are updated too. This enables live theme
switching!
You can also add class names to the same element via options.classNames
, which
is a string[]
.
See: React Hooks API Reference | useLayoutEffect
Returns: the result of
React.useContext
In the project directory, you can run:
Launches the [Jest][https://jestjs.io/] test runner in the interactive watch mode.
For a coverage report, run npm test -- --coverage
.
Runs ESLint.
Runs commitizen, prompting you to fill out any required commit fields at commit time.
Builds the library for npm into the dist
folder.