Skip to content

Instantly share code, notes, and snippets.

@JacobJaffe
Created February 8, 2022 23:56
Show Gist options
  • Save JacobJaffe/a4f2467ad41da94fa3477a47c477fb40 to your computer and use it in GitHub Desktop.
Save JacobJaffe/a4f2467ad41da94fa3477a47c477fb40 to your computer and use it in GitHub Desktop.
React Native Mapped Style Generation
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