jpudysz / react-native-unistyles

Level up your React Native StyleSheet

Home Page:https://unistyl.es

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

PlatformColor gets converted to undefined by parseStyle function

khagesh opened this issue · comments

Description

We are using PlatformColor for setting all colors inside our app. But when we pass a style object to createStyleSheet, then these PlatformColor gets converted to undefined. And hence the color does not gets applied to component. This is only happening for Android and iOS, web is working fine.

After digging into code, I found the reason. It was because inside parseStyle function we are checking if we see style properties value as object, then we proceed assuming that the value is for breakpoints, which is a valid assumption as per this library objective. But, this is where PlatformColor breaks. Since, PlatformColor value is also an object, the value gets converted to undefined by getValueForBreakpoint function in breakpoints.ts.

I am not sure what is the correct way to fix it. I can think of two ways to fix it.

First, we add checks for PlatformColor and return value as it is inside parseStyle function. This is the patch that I made for myself and patching this library locally.

diff --git a/node_modules/react-native-unistyles/src/utils/styles.ts b/node_modules/react-native-unistyles/src/utils/styles.ts
index c35c333..c44b242 100644
--- a/node_modules/react-native-unistyles/src/utils/styles.ts
+++ b/node_modules/react-native-unistyles/src/utils/styles.ts
@@ -97,6 +97,16 @@ export const parseStyle = <T, B extends Breakpoints>(
                     return [key, value]
                 }
 
+                // if the value is a PlatformColor Object, we don't want to parse it
+                if (value && typeof value === 'object' && value.hasOwnProperty('semantic')) {
+                    return [key, value]
+                }
+
+                // or on Android the property to check is resource_paths
+                if (value && typeof value === 'object' && value.hasOwnProperty('resource_paths')) {
+                    return [key, value]
+                }
+
                 return [
                     key,
                     getValueForBreakpoint<B>(

Second, we can return the value as it is, instead of returning undefined, inside breakpoints.ts file's getValueForBreakpoint function.

    return breakpointPairs.length > 0
        ? value[availableBreakpoints[availableBreakpoints.length - 1] as keyof B & string]
        : undefined

Steps to reproduce

  1. Define a PlatformColor
  2. Pass PlatformColor value to any style property
  3. console.log after useStyles hook to see that PlatformColor value is converted to undefined.

Snack or a link to a repository (optional)

No response

Unistyles version

1.1.6

React Native version

0.72.6

Platforms

Android, iOS

Cool case and thanks for the hints about the patch. I will be happy to add support for PlatformColors 🙏