Created
February 8, 2022 23:56
-
-
Save JacobJaffe/a4f2467ad41da94fa3477a47c477fb40 to your computer and use it in GitHub Desktop.
React Native Mapped Style Generation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { StyleSheet, ViewStyle } from "react-native"; | |
type ValueOf<T> = T[keyof T]; | |
type mapFunc<V extends ValueOf<ViewStyle>> = ( | |
key: string, | |
value: V | |
) => ViewStyle; | |
/** | |
* Creates a style object from a map of key-value pairs. | |
* @example | |
* const horizontalPaddingStyles = | |
* createMappedStyle("horizontalPadding", { sm: 2, md: 4 }); | |
*/ | |
export function createMappedStyle< | |
T extends keyof ViewStyle, | |
V extends ViewStyle[T], | |
M extends { [key: string]: V } | |
>(style: T | mapFunc<ValueOf<M>>, map: M) { | |
return StyleSheet.create( | |
Object.entries(map).reduceRight( | |
(acc, [key, value]) => ({ | |
...acc, | |
[key]: | |
typeof style === "string" | |
? { | |
[style]: value, | |
} | |
: style(key, value as ValueOf<M>), | |
}), | |
{} | |
) as { [key in keyof M]: ViewStyle } | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment