Skip to content

Setup

Setup

Install library

Terminal window
yarn add react-native-unistyles

Define your theme

You don’t have to follow a specific format. Just make an object and add any keys/values you like.

theme.ts
export const theme = {
colors: {
blood: '#eb4d4b',
barbie: '#e056fd',
pumpkin: '#f0932b',
background: '#ffffff'
},
margins: {
sm: 2,
md: 4,
lg: 8,
xl: 12
}
} as const

or something more advanced with nested objects / functions:

theme.ts
export const theme = {
colors: {
blood: '#eb4d4b',
barbie: '#e056fd',
pumpkin: '#f0932b',
background: '#ffffff'
},
components: {
typography: {
bold: {
fontWeight: 'bold'
},
thin: {
fontWeight: '300'
}
}
},
margins: {
sm: 2,
md: 4,
lg: 8,
xl: 12
},
utils: {
hexToRGBA: (hex: string, opacity: number) => {
const rgb = hex
.replace('#', '')
.split(/(?=(?:..)*$)/)
.map(x => parseInt(x, 16))
return `rgba(${rgb.at(0)}, ${rgb.at(1)}, ${rgb.at(2)}, ${opacity})`
}
}
} as const

It’s good to add “as const” to the end of your theme object to make sure TypeScript knows it’s a constant object and not a mutable one. It also allows you to spread your partial theme object into a full theme object without TypeScript complaining.

Create breakpoints

There are no predefined breakpoints. You can name them anything. Just make an object with string keys and number values.

breakpoints.ts
export const breakpoints = {
xs: 0,
sm: 576,
md: 768,
lg: 992,
xl: 1200,
superLarge: 2000,
tvLike: 4000
} as const

It’s good to add “as const” to the end of your breakpoints object to make sure TypeScript knows it’s a constant object and not a mutable one.

Wrap your app with UnistylesTheme to inject theme

import React from 'react'
import { UnistylesTheme } from 'react-native-unistyles'
import { theme } from './theme'
export const App: React.FunctionComponent = () => (
<UnistylesTheme theme={theme}>
// Your App
</UnistylesTheme>
)

Access createStyleSheet and useStyles with a factory

styles.ts
// import library factory
import { createUnistyles } from 'react-native-unistyles'
// import your breakpoints, add whatever keys and numeric values you want
import { breakpoints } from './breakpoints'
// import your app's theme TypeScript type, or simply use 'typeof theme'
import { theme } from './theme'
export const {
createStyleSheet,
useStyles,
} = createUnistyles<typeof breakpoints, typeof theme>(breakpoints)