Skip to content

createUnistylesComponent

createUnistylesComponent

Before reading this guide, make sure that you understand How Unistyles works and how Babel plugin manipulates your code.

Why do you need it?

  • Unistyles cannot retrieve ShadowNode from third-party components because they might not expose a native view via the ref prop
import { Blurhash } from 'react-native-blurhash'
const MyComponent = () => {
return
<Blurhash
blurhash="LGFFaXYk^6#M@-5c,1J5@[or[Q6."
// 💥 Oops! Blurhash is 3rd party view, that might not expose the `ref` prop
// it will never update when theme changes
style={styles.container}
/>
}
}
const styles = StyleSheet.create(theme => ({
container: {
borderWidth: 1,
borderColor: theme.colors.primary
}
}))
  • Another use case is when you use components that do not expect a style prop but require, for example, a color prop.
import { Button } from 'react-native'
const MyComponent = () => {
return (
<Button
// 💥 Oops! Button is React Native component, so it has a ref, but it doesn't expect `style` prop
// it will never update when theme changes
// Also, from where will we get `theme` value?
color={theme.colors.primary}
/>
)
}

That’s why we created a way to subscribe such component to Unistyles updates.

Auto mapping for style and contentContainerStyle props

If your component expects the style or contentContainerStyle prop, Unistyles will automatically handle the mapping under the hood. You just need to wrap your custom view in createUnistylesComponent. We will also respect your style dependencies, so, for example, the Blurhash component will only re-render when the theme changes.

import { Blurhash } from 'react-native-blurhash'
import { createUnistylesComponent } from 'react-native-unistyles'
// ✨ Magic auto mapping
const UniBlurHash = createUnistylesComponent(Blurhash)
const MyComponent = () => {
return (
<UniBlurHash
blurhash="LGFFaXYk^6#M@-5c,1J5@[or[Q6."
// now Blurhash will re-render when theme changes
style={styles.container}
/>
)
}

Mapping custom props to Unistyles styles

If you need to ensure your component updates but it doesn’t use style or contentContainerStyle props, you can use mappings:

import { Button } from 'react-native'
import { createUnistylesComponent } from 'react-native-unistyles'
// ✨ Some magic happens under the hood
const UniButton = createUnistylesComponent(Button, theme => ({
// map `primary` color to `color` prop
color: theme.colors.primary
}))
const MyComponent = () => {
return (
// you don't need to specify color props here
<UniButton />
)
}

TypeScript will autocomplete all your props, so there is no need to specify type manually.