Skip to content

Dynamic themes

Theming

You can incorporate as many themes as you desire in your application. While there’s flexibility in how you structure your theme, it’s essential to maintain consistency with the TypeScript type:

To promote reusability and maintainability, it’s a good practice to share as many values between themes as possible:

// move shared colors to object
const sharedColors = {
    barbie: '#ff9ff3',
    oak: '#1dd1a1',
    sky: '#48dbfb',
    fog: '#c8d6e5',
    aloes: '#00d2d3'
}

export const lightTheme = {
    colors: {
        // reuse or override them
        ...sharedColors,
        backgroundColor: '#ffffff',
        typography: '#000000'
    }
    // other keys in common with darkTheme
}

export const darkTheme = {
    colors: {
        // reuse or override them
        ...sharedColors,
        backgroundColor: '#000000',
        typography: '#ffffff'
    }
    // other keys in common with lightTheme
}

// export type that will be used to describe your theme
export type AppTheme = typeof lightTheme | typeof darkTheme

With the themes set up, modify your createUnistyles to consume your AppTheme type:

export const { useStyles, createStyleSheet } = createUnistyles<typeof breakpoints, AppTheme>(breakpoints)

The final step is to switch your theme based on certain states, persisted values, databases, etc.:

export const App: React.FunctionComponent = () => {
    // obtain here your dark or light theme. It can be storage, state, mmkv, or whatever you use
    // const [yourAppTheme] = useState(lightTheme)
    // const [yourAppTheme] = useYourStorage()
    // const [yourAppTheme] = useMMKVObject<AppTheme>(Theme)

    // switching theme will re-render your stylesheets automatically
    return (
        <UnistylesTheme theme={yourAppTheme}>
            <Examples.Extreme />
        </UnistylesTheme>
    )
}