withUnistyles
Before reading this guide, make sure that you understand How Unistyles works and how Babel plugin manipulates your code. Also read our decision algorithm to learn when to use this factory.
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
- Another use case is when you use components that do not expect a
style
prop but require, for example, acolor
prop.
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 withUnistyles
. We will also respect your style dependencies, so, for example, the Blurhash
component will only re-render when the theme changes.
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
:
TypeScript will autocomplete all your props, so there is no need to specify type manually.
Custom mappings for external props
Sometimes, you might want to map your props based on a function or value that is only accessible within the component.
For example, if you are using FlashList
and want to modify the numColumns
prop based on a condition. Using mappings
in withUnistyles
is not an option because it doesn’t allow referencing other props.
Another example is React Native’s Switch
component:
For such dynamic mappings, we provide a prop called uniProps
that allows you to pass any props to the component.
From there, you can access any function or variable or map the prop to any value based on your state and needs.
uniProps
is a function that receives theme
and rt
as arguments. These values will be always up-to-date, so you can use them to map colors or value to new props.
Props resolution priority
We will respect your order of prop resolution, applying them with the following priority:
- Global mappings
uniProps
- Inline props
Example: Modifying a Button