Last active
October 5, 2023 16:28
-
-
Save babacarMbengue12/05ee23a634589f8395a8f43ab35fb6c0 to your computer and use it in GitHub Desktop.
How to customise react native view and add custom props
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 React, { ReactNode } from "react"; | |
import { View as ReactView, ViewStyle } from "react-native"; | |
export type CustomProps = Partial<{ | |
mt: number | "auto"; | |
mb: number | "auto"; | |
my: number | "auto"; | |
mx: number | "auto"; | |
ml: number | "auto"; | |
mr: number | "auto"; | |
px: number | "auto"; | |
py: number | "auto"; | |
pb: number | "auto"; | |
pt: number | "auto"; | |
pl: number | "auto"; | |
pr: number | "auto"; | |
ai: ViewStyle["alignItems"]; | |
jc: ViewStyle["justifyContent"]; | |
bg: string; | |
row: boolean; | |
flex: boolean | number; | |
fz: number; | |
color: string; | |
}>; | |
const supports: (keyof CustomProps)[] = [ | |
"fz", | |
"ai", | |
"bg", | |
"flex", | |
"jc", | |
"mb", | |
"ml", | |
"mr", | |
"mt", | |
"mx", | |
"my", | |
"pb", | |
"pl", | |
"pr", | |
"pt", | |
"row", | |
"py", | |
"px", | |
]; | |
type ViewProps = Partial<{ | |
style: ViewStyle; | |
children: ReactNode; | |
}> & | |
CustomProps; | |
export function View({ style, ...rest }: ViewProps) { | |
const { style: newStyles, otherProps } = getStyles(style, rest); | |
return <ReactView style={newStyles} {...otherProps} />; | |
} | |
export function getStyles( | |
styles: any, | |
{ bg, flex, row, fz, ...rest }: CustomProps | |
) { | |
const newProps: any = {}; | |
const newStyles: any = { | |
backgroundColor: bg, | |
flex: flex === true ? 1 : flex, | |
flexDirection: row ? "row" : "column", | |
fontSize: fz, | |
...styles, | |
}; | |
type Prop = keyof typeof rest; | |
for (const prop of Object.keys(rest)) { | |
const key = prop as Prop; | |
if (supports.includes(key)) { | |
newStyles[getProp(key)] = rest[key]; | |
} else { | |
newProps[key] = rest[key]; | |
} | |
} | |
return { style: newStyles, otherProps: newProps }; | |
} | |
function getProp(prop: string) { | |
const [letter1, letter2] = prop.split(""); | |
const obj = { | |
m: "margin", | |
p: "padding", | |
t: "Top", | |
l: "Left", | |
y: "Vertical", | |
x: "Horizontal", | |
b: "Bottom", | |
r: "Right", | |
i: "Items", | |
j: "justify", | |
a: "align", | |
c: "Content", | |
bg: "Color", | |
}; | |
type KeyObj = keyof typeof obj; | |
return `${obj[letter1 as KeyObj]}${ | |
obj[letter2 as KeyObj] | |
}` as keyof ViewStyle; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment